【发布时间】:2017-03-25 06:07:58
【问题描述】:
下面的代码按这样的顺序工作
-->then 1
-->then 2
-->then 3
-->then 3 ends
-->then 4
-->then 5
--> x
--> y
--> x
--> y
-->then 6
但我希望它是这样的:
-->then 1
-->then 2
-->then 3
--> x
--> y
--> x
--> y
-->then 3 ends
-->then 4
-->then 5
-->then 6
这是代码: 问题出在 forEach 中。 如果我在 forEach 中有一次(“值”)的东西,我无法等待它的结果然后继续“然后 4”
let massUpdate={};
let licenseLength=0;
let refOfferLength =admin.database().ref()...
refOfferLength.once("value")
.then(lengthSnapshot=>{
console.log(" then :1 ");
//....
}).then(snap=>{
console.log(" then :2 ");
let ref = admin.database().ref()....
return ref.once("value");
}).then(ref=>{
console.log(" then :3 ");
ref.forEach(function(pSnapshot){
let pId = pSnapshot.key;
let pPath = pSnapshot.val();
let refP = admin.database().ref().child("asd").child(event.params.userId).child(pPath).child(pId);
refP.once("value").then(snap=>{
console.log(" then :x ");
//.....
let path_license = "asd/" + event.params.userId+"/"+urunPath+"/"+urunId+"/license";
let val_license = "open";
//....
massUpdate[path_license]=val_license;
}).then(snap=>{console.log(" then :y ");});
});
console.log(" then :3 ends");
}).then(snap=>{//
console.log(" then :4 ");
let pathOffersAndUsers = "kpss_offers_and_users/"+event.params.offerId+"/"+event.params.userId;
let valOfferDetails = {"created_date": (moment().utcOffset(3).format("Y-MM-DD HH:mm:ss"))};
massUpdate[pathOffersAndUsers]=valOfferDetails;
return true;
}).then(snap=>{//
console.log(" then :5 ");
let ref = admin.database().ref();
return ref.update(massUpdate);
}).then(snap=>{
console.log(" then :6 ");
console.log(" Done : "+ event.params.userId + " : "+ event.params.offerId);
}).catch(function (error){console.log(" E : "+error+" : "+ event.params.userId + " : "+ event.params.offerId);});
【问题讨论】:
-
呃,don't use
forEachwith promises(或其他)?