繁体   English   中英

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

[英]how to handle the return of a javascript function with nested Parse.Promises inside

我有这个功能:

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

我如何才能将退货放入最后一个退货中,或者以某种方式将其链接起来?

您需要从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");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM