shirha
shirha

Reputation: 497

position of await in statement syntax clarification

I saw this code snippet today and this is the first time I have seen await in this position. I would have never thought to put it here.

for await (const req of s) {
  req.rspond({body: “Hello world\n” });
}

I would have put it before req (the actual async command)

for (const req of s) {
  await req.rspond({body: “Hello world\n” });
}

I used a similar pattern in my puppeteer code.

  for (let i of a) {
      await page.click(sel);
      await page.waitFor(wait);
}

My question is, would this still work correctly if I coded it like this?

  for await (let i of a) {
      page.click(sel);
      page.waitFor(wait);
}

And apply the await to all async commands? Where does await belong?

Upvotes: 0

Views: 38

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

No - for await is a special way for interacting with objects which expose an async iterable interface:

const wait = () => new Promise(resolve => setTimeout(resolve, 500));
const obj = {
  async *[Symbol.asyncIterator]() {
    for (let i = 0; i < 3; i++) {
      // fetching item...
      await wait();
      yield i;
    }
  }
};

(async () => {
  for await (const item of obj) {
    console.log(item);
  }
})();

If you have a normal iterator, like you do with const req of s, and you need to call an asynchronous function for each item yielded by the iterator, then your current code is still the only way to do it, eg:

for (const req of s) {
  await req.rspond({body: “Hello world\n” });
}

Async iterators are useful for when the items being yielded are generated asynchronously. They don't imply anything about the items after they're yielded from the generator.

Upvotes: 1

Related Questions