循环中出现意外的"等待".(无AWAIT在回路)

Sed*_*rei 12 javascript async-await

我该如何等待bot.sendMessage()循环内部?
也许我需要,await Promise.all但我不知道我应该如何添加bot.sendMessage()

码:

  const promise = query.exec();
  promise.then(async (doc) => {
    let count = 0;
    for (const val of Object.values(doc)) {
      ++count;
      await bot.sendMessage(msg.chat.id, ` ${count} and ${val.text}`, opts);
    }
  }).catch((err) => {
    if (err) {
      console.log(err);
    }
  });
Run Code Online (Sandbox Code Playgroud)

错误:

[eslint] Unexpected `await` inside a loop. (no-await-in-loop)
Run Code Online (Sandbox Code Playgroud)

Pat*_*rts 19

如果你需要一次一个地发送每条消息,那么你所拥有的就好了,根据文档,你可以忽略这样的eslint错误:

const promise = query.exec();
promise.then(async doc => {
  /* eslint-disable no-await-in-loop */
  for (const [index, val] of Object.values(doc).entries()) {
    const count = index + 1;
    await bot.sendMessage(msg.chat.id, ` ${count} and ${val.text}`, opts);
  }
  /* eslint-enable no-await-in-loop */
}).catch(err => {
  console.log(err);
});
Run Code Online (Sandbox Code Playgroud)

但是,如果您能够并行发送它们,则应该执行此操作以最大化性能和吞吐量:

const promise = query.exec();
promise.then(async doc => {
  const promises = Object.values(doc).map((val, index) => {
    const count = index + 1;
    return bot.sendMessage(msg.chat.id, ` ${count} and ${val.text}`, opts);
  });

  await Promise.all(promises);
}).catch(err => {
  console.log(err);
});
Run Code Online (Sandbox Code Playgroud)


gui*_*job 8

await一旦迭代在大多数情况下没有依赖性,就可以避免执行内部循环,这就是为什么在这里eslint警告它

您可以将代码重写为:

const promise = query.exec();
  promise.then(async (doc) => {
    await Promise.all(Object.values(doc).map((val, idx) => bot.sendMessage(msg.chat.id, ` ${idx + 1} and ${val.text}`, opts);)
  }).catch((err) => {
    if (err) {
      console.log(err);
    }
  });
Run Code Online (Sandbox Code Playgroud)

如果您仍然要发送一对一的消息,则您的代码没问题,但是 eslint 您一直在抛出此错误

  • 不要像这样混合 `.then()`/`.catch()` 和 `async`/`await` 语法 (3认同)