bbusdriver
bbusdriver

Reputation: 1627

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);
}

Upvotes: 3

Views: 986

Answers (1)

Phillip
Phillip

Reputation: 6253

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');
    }
  }
})();

Upvotes: 1

Related Questions