Javascript async map early early
问题描述:
我正在尝试为数组中的每个项目异步查询Firebase Cloud Firestore。我对async.map函数的理解是,它会对数组中的每个项目执行一个函数,并且只有在处理完所有项目后才触发它的回调。但是,下面的回调会在第一次查询后立即执行,并且在任何结果可用之前立即执行。什么是最好的方法来做到这一点?Javascript async map early early
var db = admin.firestore();
var getData = function (item, doneCallback) {
db.collection('myCollection').doc(item).get()
.then(results => {
console.log("Callback here");
return doneCallback({
"name": results.data().name,
"id": results.data().id,
"phone": results.data().phone,
});
});
};
async.map(myArray, getData, function (err, results) {
console.log("Finished");
for (var i=0;i<results.length; i+=1){
console.log(results[i].name);
console.log(results[i].id);
console.log(results[i].phone);
}
});
答
避免async.js另一种方法(我个人觉得很难回调代码阅读,承诺最终会被更统一):
var db = admin.firestore();
var promises = [];
for (var i = 0; i < myArray.length; i++){
var promise = db.collection('myCollection').doc(myArray[i]).get()
.then(results => {
console.log("Callback here");
return {
"name": results.data().name,
"id": results.data().id,
"phone": results.data().phone,
};
});
promises.push(promise);
}
Promise.all(promises).then(results,() => {
console.log("Finished");
for (var i = 0; i < results.length; i++){
console.log(results[i].name);
console.log(results[i].id);
console.log(results[i].phone);
}
});
答
在问题的代码不return
的Promise
从getData()
通话,看到Why is value undefined at .then() chained to Promise?
var getData = function(item, doneCallback) {
// `return` the `Promise` object from the function
return db.collection('myCollection').doc(item).get()
.then(results => {
console.log("Callback here");
return doneCallback({
"name": results.data().name,
"id": results.data().id,
"phone": results.data().phone,
});
});
};