JS change old async code to "synchronize"

11 Aug 2020

Some times you will get an async function API from some lib which is use the old callback way to do async works. It’s hard to organize and will get a low readability most time. Then we can use Promise and async/await to change it to “synchronize”.

Example: (Cocos Creator)

cc.loader.loadRes("map", cc.TiledMapAsset, (error, assest) => {
  // Further works

“Synchronize” it:

async function loadRes(...args) {
  return new Promise((resolve, reject) => {
    cc.loader.loadRes(...args, function (error, resource) {
      if (error === null) {
      } else {

async function setup() {
  const asset = await loadRes("map", cc.TiledMapAsset)
  // Further works


See, we use Promise and async/await to change an old async code to “synchronize”.

Back to top