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

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

Leave a Comment