循环内出现意外的 \`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);
    }
});

错误:

 [eslint] Unexpected `await` inside a loop. (no-await-in-loop)

原文由 Saeed Heidarizarei 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.6k
2 个回答

如果您需要一次发送一条消息,那么您所拥有的就可以 了,根据文档,您可以像这样忽略 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);
});

但是,如果发送消息不需要顺序,您应该改为这样做以最大化性能和吞吐量:

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

原文由 Patrick Roberts 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

如果你仍然发送一个接一个的消息,你的代码没问题,但是 eslint 你一直抛出这个错误

原文由 guijob 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏