我有一个两步火力基地火库代码。第一步在线抓取所有用户,第二步检查learning_language相等。第一步生成一个地图循环,用于遍历所有在线用户。但是控制台.log最后返回一个空数组。
db.collection(ns_status).where("state", "==", "online").onSnapshot(function(snapshot) {
var ns_match = snapshot.docs.map(function(userSnapshot) {
db.collection(ns_profile).doc(userSnapshot.id).get().then(function(doc) {
spoken_language = doc.data().spoken_language;
if (learning_language == spoken_language) {
return (userSnapshot.id);
}
})
})
console.log(ns_match);
})
如何在最后获取正确存储的数组?我觉得这是一个异步问题。
提前谢谢。
如果我理解正确,您希望获取按以下条件过滤的userSnaphot
文档数组:
learning_language == doc.data().spoken_language
这里的一种方法可能是使用 Array#filter(( 方法来实现此目的,您将使用上面的匹配条件来过滤与所需learning_language
匹配的用户文档。
要获取过滤的用户文档数组作为结果ns_match
变量,您需要解析一个 promise 数组,看到您正在为 snapshot.docs
数组中的每个项目执行 promise of db.collection(ns_profile).doc(userSnapshot.id).get()
。
您可以使用Promise.all()
函数来实现此目的,详见以下注释:
db.collection(ns_status)
.where("state", "==", "online")
.onSnapshot(function(snapshot) {
/*
Return the promise so that resolved ns_match array can be used externally
*/
return Promise.all(snapshot.docs.map((userSnapshot) => {
/*
For each document in docs, map each to a promise. Once all of
these promises are resolved, Promise.all() will pass the array
of documents to the next then() handler
*/
return db.collection(ns_profile).doc(userSnapshot.id).get();
}))
.then(users => {
/*
We now have a list of user documents in users. It seems like
the filter method is better suited to what you're wanting, so
filter user documents based on the condition that
spoken_language === learning_language
*/
return users.filter(doc => {
const spoken_language = doc.data().spoken_language;
return learning_language === spoken_language;
});
})
.then(ns_match => {
/*
We now recieve the list of filtered user documents where the
language ns_match applies for all items in ns_match
*/
console.log(ns_match);
/* Return this filtered array for use outside of this call */
return ns_match;
})
})
希望对您有所帮助!