解析承诺。在Promises中访问变量

时间:2014-02-24 18:52:05

标签: parse-platform

解析承诺。我是使用Promise的新手。下面相当简单的例子。所以,我从一个Promise得到的结果,我不知道如何将它传递给下一个Promise。想法非常感谢!我尝试过几个想法。除了最后一个"硬编码"之一。

}).then(function(results) {

      var BsellerObjectId = results.id;  
      alert ("WHOO-HOO!  Saved" + BsellerObjectId);

}).then(function(valedictorian) {

      var BumpSold = Parse.Object.extend("BumpSold");
      var BumpSold = new BumpSold();
      BumpSold.id = "QmJNz4x2EC";                                      

  return BumpSold.save({ BsellerObjectId: BsellerObjectId});        // doesn't work
  return BumpSold.save({ BsellerObjectId: results.id});             // doesn't work
  return BumpSold.save({ BsellerObjectId: "Hello"});                // WORKS!   

1 个答案:

答案 0 :(得分:0)

假设你正在使用自定义Promises,你可以通过promise数据的成功回调将Promise的结果传递给另一个。

extends.foo = function(){

    var promise = new Parse.Promise();

    var query = new Parse.Query(Parse.User);
    query.equalTo("name","Joe");
    query.find().then(function(results) {        

      if (results.length > 0)
        promise.resolve(results[0]);
      else
        promise.reject(-2);

    }, function(error) {
        promise.reject(-1);
    });

    return promise;
}


extends.foo2 = function(){

    var promise = new Parse.Promise();

    this.foo().then(function(result){

      // success case
      promise.resolve({uselessParam:123,firstResult:result})


    },function(error){

      // error case
      promise.reject(error); // so, -1 or -2 returned by the promise in foo()

    });
    return promise;
}


// usage

extends.foo3 = function(){

    this.foo2().then(function(result){

      console.log(result.uselessParam); // added in the foo2()
      console.log(result.firstResult); // returned by the foo() and added again in the foo2() 

    },function(error){

      console.log(error); // so, -1 or -2 returned by the promise in foo()

    });
}

您还可以在main函数中定义一个使用promises的变量(但是从它们中取出),然后通过promise承诺

希望它有所帮助!