数组已初始化
var Collect = [];
所以我有一个promise参数,这样我就可以执行异步操作,因为从firebase中检索数据然后推入数组Collect需要一些时间。这是我的代码:
function loadTables(){
var promise = getDataFirebase();
promise.then(function(){
console.log("firsst");
return ProcessOfData();
}).then(function(){
console.log(Collect); //when printed, it shows the elements collected from firebase so the array is not 0.
console.log(Collect.length); // but when printeed here. it gives me 0. why?
return EndProcessLog();
}).then(function(){
});
}
从firebase检索数据时的代码:
function getDataFirebase(){
return new Promise (function(resolve,reject){
refReview.on("value", function(snap){
var data = snap.val();
for(var key in data){ //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT
Collect.push({
"RevieweeName": data[key].revieweeID.firstname.concat(" ",data[key].revieweeID.lastname),
"ReviewerName": data[key].reviewerID.firstname.concat(" ",data[key].reviewerID.lastname),
rating:data[key].rating,
content: data[key].content
})
}//end of for loop
}); //end of snap
resolve();
});
}
答案 0 :(得分:2)
为什么不起作用?因为您在异步方法运行之前解析了promise。对象显示值的原因是控制台延迟加载对象。
你做什么的?在回调中的for循环之后移动解析行。
refReview.on("value", function(snap) {
var data = snap.val();
for (var key in data) { //data retrieved must be REVIEWEE NAME, REWIEVER NAME, RATING, ,CONTENT
Collect.push({
"RevieweeName": data[key].revieweeID.firstname.concat(" ", data[key].revieweeID.lastname),
"ReviewerName": data[key].reviewerID.firstname.concat(" ", data[key].reviewerID.lastname),
rating: data[key].rating,
content: data[key].content
})
} //end of for loop
resolve(); < --RIGHT
}); //end of snap
// resolve(); <-- WRONG
理想情况下,如果您不使用全局变量,则可以通过解析传递值。
var myPromise = new Promise(function(resolve, reject) {
var str = "Hello!";
resolve(str);
});
myPromise.then(function(value) {
console.log(value);
});
&#13;