如何在foreach循环中等待异步函数

时间:2021-05-04 07:24:59

标签: node.js

我有一些这样的代码,value.users.fetch() 返回一个承诺:

console.log('1');

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

});

console.log('3');

输出:

1
3
<some data here>

但我希望它是:

1
<some data here>
3

无论如何要在 forEach 循环中等待 value.users.fetch() 返回?

1 个答案:

答案 0 :(得分:3)

forEach 方法不会等待 async 操作结束,然后再进行下一次迭代。

您可以将 async-await 语法与 for of 循环一起使用

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