我在 FCM 上工作, channel /房间中的所有成员都需要设备 token 来发送推送通知,并且每个成员都有多个设备,为此我需要两个 for 循环。
我将 async/await 与 firestore 查询一起使用,但它不等待结果,在后台处理它并移动到需要结果数据的下一个语句。
const notification = async (channelId) => {
let tokens = []
const members = await db.collection('channels/' + channelId + '/members').get();
await members.forEach(async (member) => {
const deviceTokens = await db.collection('users/' + member.id + '/devices').get();
await deviceTokens.forEach(async (token) => {
console.log(token.id);
await tokens.push(token.data().token);
})
})
console.log(tokens);
return await sendPush(tokens); // calling other functions
}
我期望输出是 tokens = ['token1', 'token2', 'token3'],但实际输出是 tokens = []
最佳答案
forEach
不能与 async..await
一起有效使用。由于查询返回 query snapshot ,应该迭代一个数组。 Promise 链可以与 for..of
串联执行或与 Promise.all
和数组 map
并行执行,如 related question 中所述。 ,例如:
const notification = async (channelId) => {
let tokens = [];
const members = await db.collection('channels/' + channelId + '/members').get();
for (const member of members.docs) {
const deviceTokens = await db.collection('users/' + member.id + '/devices').get();
for (const deviceToken of deviceTokens.docs) {
tokens.push(deviceToken.data().token);
}
}
return await sendPush(tokens);
}
await sendPush(...)
仅当 sendPush
返回 promise 时才能正常工作。
关于node.js - 是否有任何解决方案可以等待嵌套的 forEach 直到在 node.js 中使用 async/await 返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747036/