2

I have some code like this, with value.users.fetch() return a promise:

console.log('1');

msg.reactions.cache.forEach(value => {
    value.users.fetch().then(data => {
        console.log(data);
    })

});

console.log('3');

Output:

1
3
<some data here>

But i want it to be:

1
<some data here>
3

Is there anyway to wait for value.users.fetch() return inside forEach loop?

1 Answer 1

3

forEach method doesn't wait for the async operation to end before moving on to the next iteration.

You can use async-await syntax along with for of loop

async function foo() {
  console.log('1');

  for (const value of msg.reactions.cache) {
    const data = await value.users.fetch();
    console.log(data);
  }

  console.log('3');
}

foo();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.