如何在Node.js的forEach循环中使用await

8

我有一个用户数组,我想检查其中有多少人已经加入了我的Telegram频道。我的检查方法是异步的,我可以像这样使用该方法:

check(user)
    .then((res) => {
    if(res) {
       // user is joined 
      }
    else {
       // user is not joined
    }
})

但是我不知道如何将此方法用于用户数组。

我已经测试了这段代码:

members = 0;
users.forEach((user) => {
            check(user)
                .then((result) => {
                    if(result) {
                          members++;
                      }
                });
        })

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

我搜索了一下,发现了一个关键字await,并在异步方法中尝试了它:

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

它能够正常工作,但当我在 forEach 循环中使用 await 时,就像这样:

users.forEach((user) => {
            await check(user)
                .then((result) => {
                    console.log(result);
                });
        })

我遇到了以下错误:SyntaxError: await is only valid in async function。我该如何处理这个神奇的forEach循环?
更新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');
  });
}

更新2:

这段代码也无效:

Promise.all(users.map(check))
            .then((Res) => {
                console.log(Res);
            })

我遇到了以下错误:
TypeError: # 不是一个函数

2
可能是在forEach循环中使用async/await的重复问题。 - Josh Lee
2个回答

11

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

为了使用 await 关键字,函数需要使用 async 关键字进行定义,例如:

users.forEach(async (user) => {
  await check(user)
    .then((result) => {
      console.log(result);
    });
  })

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

要正确地实现它,你可以使用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, ...]
})

0
你可以使用内置的forEach函数,然后在回调函数中处理结果,这里推荐使用async库。这是一个很棒的教程here
编辑 - 这里有Sebastian Eilund的示例:
async.forEach(users, function(user, callback) {
  //do stuff
  callback();
}, function (err) {
  //finished doing stuff for all users
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接