如何处理内置嵌套Parse.Promises的javascript函数的返回

时间:2014-07-24 21:25:39

标签: javascript parse-platform promise

我有这个功能:

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! 
}

thisDlastDParse.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());
  });

我怎样才能把回报放在最后一个,或以某种方式链接它?

1 个答案:

答案 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");
});
相关问题