var count=0;
function test2(callback) {
db.doc("Kerala/Pathanamthitta")
.listCollections()
.then((snap) => {
snap.forEach((collection) => {
var col = collection.id;
db.collection(`Kerala/Pathanamthitta/${col}`)
.where("completionStatus", "<", 3)
.get()
.then((snapshot) => {
snapshot.forEach((doc) => {
var data = doc.data();
console.log(data.place);
if (data.completionStatus == 0) count++;
});
});
});
})
.then(callback);
}
test2(function () {
console.log(count);
});
我想在执行test2函数后打印最终计数。即使函数test2内部发生任何更新,它也会打印该语句,但始终为0。我试图做一个callback()但还是一样 请帮忙。预先感谢
答案 0 :(得分:1)
您误会了异步函数和Promise链的工作方式。您正在紧接彼此调用一个Promise链和回调。
db.doc(...)...
callback()
最终执行如下:
db.doc
callback
db.doc.then
至此,您已经在答应链的解析之前调用了回调。您希望将回调放入promise链中,以便将其延迟到所有回调完成之后。一个好地方是在外循环之后的另一个promise链中,用于最终计数的单个日志。
...
.then(snap => {
snap.forEach(collection => {...});
})
.then(callback);
...
这样,当您完成所有快照的操作并完成对快照的计数之后,您将在两次遍历之后以正确的顺序打印出计数。
但是仍然在打印0。为什么呢?好吧,我们没有正确地履行诺言。我们需要确保在promise链中创建的所有promise都正确,以便在进入日志记录步骤时,我们已经有了正确的链。
完整代码:
var count = 0;
function test2(callback) {
db.doc("Kerala/Pathanamthitta")
.listCollections()
.then((snap) => {
return Promise.all(
snap.map((collection) => {
var col = collection.id;
return db
.collection(`Kerala/Pathanamthitta/${col}`)
.where("completionStatus", "<", 3)
.get()
.then((snapshot) => {
return Promise.all(
snapshot.map((doc) => {
var data = doc.data();
console.log(data.place);
if (data.completionStatus == 0) count++;
})
);
});
})
);
})
.then(callback);
}
test2(function () {
console.log(count);
});
答案 1 :(得分:0)
with()