我有一个用户数组,我想检查其中有多少人已经加入了我的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: # 不是一个函数