William Taylor
William Taylor

Reputation: 619

how to wait for async function in foreach loop

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?

Upvotes: 2

Views: 1261

Answers (1)

Yousaf
Yousaf

Reputation: 29282

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

Upvotes: 3

Related Questions