71

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)
5
  • Do the messages need to send one at a time or all at once? Feb 23, 2018 at 22:27
  • with this code I have message 1 after that 2 and ... but messages is not ordered Feb 23, 2018 at 22:29
  • 2
    You haven't answered the question. Which do you want? Feb 23, 2018 at 22:30
  • 1
    I Don't understand, But I want to send Messages one by one by ordered Feb 23, 2018 at 22:32
  • 1
    why don't you use promise.all? like await Promise.all(Object.values(doc).map((val, idx) => bot.sendMessage(msg.chat.id, `💬 ${idx} and ${val.text}`, opts);)
    – guijob
    Feb 23, 2018 at 22:35

4 Answers 4

109

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);
});
2
  • I want to use this code to get user messages and Show those Messages to them, Is this way fit to my question? Feb 23, 2018 at 22:45
  • 1
    @SedricHeidarizarei The first block will silence the eslint error you were getting. The second one is not functionally equivalent, but if it works for you, then that's probably preferable since it's more efficient. Feb 23, 2018 at 22:53
11

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

1
  • 3
    Don't mix .then()/.catch() and async/await syntax like that
    – Bergi
    Apr 11 at 20:35
2

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
}

2

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);
};  
2
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jan 13, 2022 at 8:34
  • This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review
    – mswgen
    Jan 17, 2022 at 5:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.