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

JavascriptAsync Await

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Performing await inside loops can be avoided once iterations doesn't have dependency in most cases, that's why eslint is warning it here

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

Solution 3 - Javascript

I had a similar issue recently, I was getting lintting errors when trying to run an array of functions in a chain as apposed to asynchronously.

and this worked for me...

const myChainFunction = async (myArrayOfFunctions) => {
  let result = Promise.resolve()
  myArrayOfFunctions.forEach((myFunct) => {
    result = result.then(() => myFunct()
  })
  return result
}

Solution 4 - Javascript

I am facing the same issue when I used await inside forEach loop. But I tried with recursive function call to iterate array.

const putDelay = (ms) =>
    new Promise((resolve) => {
        setTimeout(resolve, ms);
    });

const myRecursiveFunction = async (events, index) => {
    if (index < 0) {
        return;
    }
    callAnotherFunction(events[index].activity, events[index].action, events[index].actionData);
    await putDelay(1);
    myRecursiveFunction(events, index - 1);
};  

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaeed HeidarizareiView Question on Stackoverflow
Solution 1 - JavascriptPatrick RobertsView Answer on Stackoverflow
Solution 2 - JavascriptguijobView Answer on Stackoverflow
Solution 3 - JavascriptCarleneView Answer on Stackoverflow
Solution 4 - JavascriptUmang PatelView Answer on Stackoverflow