如何在nodejs的forEach循环中使用await

Ala*_*412 6 node.js

我有一组用户,我想检查他们中有多少人加入了我的电报频道,我的检查方法是异步方法,我可以使用这样的方法:

check(user)
    .then((res) => {
    if(res) {
       // user is joined 
      }
    else {
       // user is not joined
    }
})
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将这种方法用于一组用户。

我已经测试了这段代码:

members = 0;
users.forEach((user) => {
            check(user)
                .then((result) => {
                    if(result) {
                          members++;
                      }
                });
        })
Run Code Online (Sandbox Code Playgroud)

但是这段代码肯定是错误的,因为我不知道什么时候应该将结果发送给我的管理员(想要检查加入了多少用户的人)。我把发送方法放在了之后,forEach但它显示了一个非常低的数字(接近 0)。

我搜索并找到了一个关键字,await并在异步方法中进行了尝试:

async function checkMembership() {
    let data;
    await check(user)
        .then((res) => {
            data = res
        });
    console.log(data);
}
Run Code Online (Sandbox Code Playgroud)

它运行良好,但是当我await像这样使用in forEach 循环时:

users.forEach((user) => {
            await check(user)
                .then((result) => {
                    console.log(result);
                });
        })
Run Code Online (Sandbox Code Playgroud)

我收到以下错误: SyntaxError: await is only valid in async function。我应该如何处理这个神奇的 forEach 循环?

UPDATE-1:我也测试过这段代码,但我得到了以前的错误:

async function checkMembership() {

    User.find({}, (err, res) => {
        for(let user of res) {
            await check(user)
                .then((ress) => {
                console.log(ress)
                })
        }
        console.log('for is finished');
  });
}
Run Code Online (Sandbox Code Playgroud)

更新-2:

此代码也不起作用:

Promise.all(users.map(check))
            .then((Res) => {
                console.log(Res);
            })
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: #<Promise> is not a function

Ser*_*bei 8

对于使用await关键字,您需要使用关键字定义函数async,例如

users.forEach(async (user) => {
  await check(user)
    .then((result) => {
      console.log(result);
    });
  })
Run Code Online (Sandbox Code Playgroud)

然而,这段代码很可能不是你想要的东西,因为它会在不等待它们完成的情况下触发异步调用(使用 async/await 和 forEach 循环

为了使其正确,您可以使用Promise.all,例如

Promise.all(users.map(check)).then((results) => {
  //results is array of all promise results, in your case it should be
  // smth like [res, false|null|undefined, res, ...]
})
Run Code Online (Sandbox Code Playgroud)