I'm working on FCM and need device tokens for all member in channel/room to send push notifications and every member have multiple devices, for that i need two for loop.
I'm using async/await with firestore queries but it not wait for result, process it in background and move to next statement which need result data.
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
}
I expect the output is tokens = ['token1', 'token2', 'token3'], but the actual output is tokens = []