我有这个功能:
function doCalculateStopBefore(thisD, lastD){
thisD.attributes.start.fetch().then(function(){
return lastD.attributes.end.fetch();
}).then(function(){
// calculate some stuff here using thisD.attributes.start and lastD.attributes.stop
thisD.set('property', value); // <--- important. update thisD!
});
return thisD; // < --- !!! this line doesn't want for the promises chain!
}
thisD
和lastD
是Parse.Objects
。我需要获取这2个字段(指向另一个解析类的指针),然后用这个值计算一些东西并更新thisD
。那我想完成这个功能...
该函数将在_.each loop
中调用,如下所示:
_.each(myCollection.models,function(thisD,index){
if (index == 0){
// first entry of user
// do not do anything.
} else{
//thisD = doCalculateStopBefore(thisD,myCollection.models[index-1]);
// above is how I had it before.
// below is my implementation of Troy's reply:
doCalculateStopBefore(thisD,myCollection.models[index-1]).then(function(thisD) {
console.log(thisD.attributes);
thisDrive = thisD;
})
}
promises.push(thisD.save());
});
我怎样才能把回报放在最后一个,或以某种方式链接它?
答案 0 :(得分:0)
您需要从doCalculateStopBefore()中的第一个fetch()返回Promise,并向其添加then()以捕获更新的值。请参阅下面的更新代码。
function doCalculateStopBefore(thisD, lastD){
return thisD.attributes.start.fetch().then(function(){
return lastD.attributes.end.fetch();
}).then(function(){
// calculate some stuff here using thisD.attributes.start
// and lastD.attributes.stop
thisD.set('property', value); // <--- important. update thisD!
return thisD;
});
}
您可以使用Parse.Promises.when()协调所有保存,在循环中调用此方法。
var promises = [];
_.each(myCollection.models, function(thisD, index) {
if (index == 0) {
// first entry of user
// do not do anything.
} else {
promises.push(doCalculateStopBefore(thisD,myCollection.models[index-1]).then(function(thisD) {
console.log(thisD.attributes);
thisDrive = thisD;
return thisD.save();
}));
}
});
Parse.Promise.when(promises).then(function() {
console.log("done");
});