我应该如何在循环中等待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)
如果你需要一次发送一条消息,那么你所拥有的就好了,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);
}
});
一旦迭代在大多数情况下没有依赖性,就可以避免在循环内执行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);
}
});
如果你仍然发送一对一的消息,你的代码是可以的,但是你会继续抛出这个错误