javascript 循环中出现意外的“await”。(无等待循环)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48957022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unexpected `await` inside a loop. (no-await-in-loop)
提问by Sedric Heidarizarei
How Should I await for bot.sendMessage()inside of loop?
Maybe I Need await Promise.allBut I Don't Know How Should I add to bot.sendMessage()
我应该如何bot.sendMessage()在循环内等待?
也许我需要,await Promise.all但我不知道我应该如何添加bot.sendMessage()
Code:
代码:
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);
}
});
Error:
错误:
[eslint] Unexpected `await` inside a loop. (no-await-in-loop)
回答by Patrick Roberts
If you need to send each message one-at-a-time, then what you have is fine, and according to the docs, you can just ignore the eslint error like this:
如果您需要一次发送每条消息,那么您所拥有的就可以了,根据 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 => {
console.log(err);
});
However, if there is no required order for sending the messages, you should do this instead to maximize performance and throughput:
但是,如果没有必要的消息发送顺序,您应该这样做以最大限度地提高性能和吞吐量:
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);
});
回答by guijob
Performing awaitinside loops can be avoided once iterations doesn't have dependency in most cases, that's why eslintis warning it here
await一旦迭代在大多数情况下没有依赖性,就可以避免执行内部循环,这就是为什么在这里eslint警告它
You can rewrite your code as:
您可以将代码重写为:
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);
}
});
If you still and to send one-after-one messages, your code is ok but eslint you keep throwing this error
如果您仍然要发送一对一的消息,则您的代码没问题,但是 eslint 您一直在抛出此错误

