Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How Should I await for bot.sendMessage() inside of loop?
Maybe I Need await Promise.all But I Don't Know How Should I add to 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) 
like image 644
Saeed Heidarizarei Avatar asked Feb 23 '18 22:02

Saeed Heidarizarei


People also ask

What happens if you use await inside a loop and what are the alternatives?

If you use await in a map , map will always return an array of promises. This is because asynchronous functions always return promises. Since map always return promises (if you use await ), you have to wait for the array of promises to get resolved. You can do this with await Promise.

Can we use await inside for loop?

Then the await keyword is used to block until the promise actually "resolves". So from the perspective of the for loop it will run synchronous. So: yes, the execution of the loop will be sequential.

Can you await without promise?

This rule applies when the await operator is used on a non-Promise value. await operator pauses the execution of the current async function until the operand Promise is resolved.

Does await wait for all promises?

The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.


1 Answers

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:

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); }); 
like image 177
Patrick Roberts Avatar answered Oct 04 '22 05:10

Patrick Roberts