循环中出现意外的“等待”。 (无AWAIT在回路)

问题描述 投票:5回答:2

我应该如何在循环中等待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)
javascript async-await
2个回答
11
投票

如果你需要一次发送一条消息,那么你所拥有的就好了,according to the docs,你可以忽略这样的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) => {
  if (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) => {
  if (err) {
    console.log(err);
  }
});

2
投票

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

您可以将代码重写为:

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

如果你仍然发送一对一的消息,你的代码是可以的,但是你会继续抛出这个错误

© www.soinside.com 2019 - 2024. All rights reserved.