[英]How to loop through an array of Firebase Firestore documents and push values into array
I am writing a Firebase Cloud Function in node.JS that reads user data from Firebase Firestore.我正在 node.JS 中编写 Firebase Cloud Function 从 Firebase Firestore 读取用户数据。 I am unable to push the token values into the token array and return all tokens at the end of the function.我无法将令牌值推送到令牌数组并返回 function 末尾的所有令牌。 My code is as follows:我的代码如下:
function getTokens(subscribers) { return new Promise(async function (resolve, reject) { const tokenArray = []; subscribers.forEach(async (subscriber) => { await firestore.collection('users').doc(subscriber).get().then((user) => { console.log("Getting user data for user: ", user); const tokens = user.data().tokens; if (tokens) { tokens.forEach((token) => { console.log("Adding token to token array"); // data is available here but does not push into tokenArray tokenArray.push(token); }); } }).catch((error) => { console.error(error); reject(error); }); }); console.log("Token Array -- Final: ", tokenArray); resolve(tokenArray); }); };
You cannot use async-await
in a forEach
loop.您不能在forEach
循环中使用async-await
。 Try mapping an array of promises and then using Promise.all()
as shown below:尝试映射一组承诺,然后使用Promise.all()
如下所示:
function getTokens(subscribers) {
return new Promise(async function (resolve, reject) {
const subscribersDocs = await Promise.all(
subscribers.map((subscriber) => {
return firestore.collection("users").doc(subscriber).get();
})
);
const tokenArray = subscribersDocs.reduce((acc, curr) => {
const tokens = curr.data().tokens;
if (tokens) {
acc = acc.concat(tokens);
}
return acc;
}, []);
console.log("Token Array -- Final: ", tokenArray);
resolve(tokenArray);
});
}
Also checkout: Using async/await with a forEach loop还结帐: 使用 async/await 和 forEach 循环
The OP code can be corrected and made more concise as follows: OP代码可以更正并更简洁如下:
async function getTokens(subscribers) {
const getUser = subscriber => firestore.collection('users').doc(subscriber).get();
const promises = subscribers.map(getUser);
const users = await Promise.all(promises);
return users.map(user => user.data().tokens).flat()
}
Some notes:一些注意事项:
async
, since it is将 function 装饰为async
,因为它是Promise.new()
, Firestore's get()
returns a promise不要使用Promise.new()
创建任何额外的 promise ,Firestore 的get()
返回 promiseget
promises in an array with map
, and run them with Promise.all()
使用get
在数组中收集承诺,并使用map
Promise.all()
运行它们data.tokens
produces an array of arrays.映射结果用户的data.tokens
会生成一个 arrays 数组。 Flatten it and you're done.把它压平,你就完成了。catch
that only throws, is just like having no catch只抛出的catch
,就像没有捕获一样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.