在语句语法澄清中的等待位置

我今天看到了这段代码,这是我第一次看到这个职位。我从没想过要把它放在这里。

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

我会把它放在req之前(实际的异步命令)

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

我在操纵p的代码中使用了类似的模式。

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

我的问题是,如果我这样编码,它是否仍然可以正常工作?

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

并将await应用于所有异步命令?等待在哪里?

评论
  • 花开则守
    花开则守 回复

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

    异步迭代器对于异步生成要生成的项目很有用。从生成器生成它们后,它们不暗示任何内容。