Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async/await slower than callback

I'm trying to convert callbacks to async/await, but found that async/await is much slower than the existing callbacks. Can anyone see what's wrong with my async/await?

for (var i = 0; i < balance; i++) {      
  tokenOfOwnerByIndex().call(i).then((id) => {           
      tokenURI().call(id).then((uri) => {
          console.log(uri);
      });
  });         
}
for (var i = 0; i < balance; i++) {
  var id = await this.getTokenOfOwnerByIndex(i);
  var uri = await this.getTokenURI(id);
  console.log(uri);
}
like image 347
bbusdriver Avatar asked Sep 13 '26 06:09

bbusdriver


1 Answers

In the first version tokenOfOwnerByIndex is called returning a promise. You attach a callback via then, and the loop continues. The promise will eventually resolve, but your for loop is done long before that.

When you use await, you are blocking following code, until the promise resolves. This means that each call to tokenOfOwnerByIndex has to resolve, before the for loop continues.

See my code for an example.

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

console.time('promise');
let c = 10;
for (let i = 0; i < 10; i++) {
  sleep(100)
    .then(() => {
      c--;
      if (c === 0) {
        console.timeEnd('promise');
      }
    });
}


console.time('await');
(async () => {
  let c = 10;
  for (let i = 0; i < 10; i++) {
    await sleep(100);
    c--;
    if (c === 0) {
      console.timeEnd('await');
    }
  }
})();
like image 105
Phillip Avatar answered Sep 14 '26 20:09

Phillip