如何加入承诺链的承诺

时间:2016-04-30 18:48:24

标签: javascript node.js promise bluebird

我有func1函数返回一个promise。在func2我已经开始了承诺链。 我想在这里做的是,我想在旧的promise链中使用func1解析消息,我希望这段代码不那么复杂。在func1

中加入func2承诺保证链的最佳方式是什么?
var func1 = function(){
  return new promise(function(resolve, reject){
    //some operations here
  });
};

var func2 = function(){
  promise.resolve(someFuncSync())
    .then(function(){
    //this is the old promise chain

        func1()
          .then(function(message,error){
             return message;
             //i want use this return value in old promise chain
          });

         console.log(message);
        //printing  func1 returned message in old promise chain
    })
};

3 个答案:

答案 0 :(得分:1)

只需从.then()处理程序中返回新的承诺,它就会自动添加到上一个链中,然后控制旧承诺链的已解析值。

在新回复的承诺得到解决且内部承诺将控制最终解决的值之前,外部承诺不会解决。我在return的电话会议前面添加了return func1()声明,将其添加到链中:

var func2 = function(){
  promise.resolve(someFuncSync())
    .then(function(){
    //this is the old promise chain

        // ADDED return here
        return func1()
          .then(function(message,error){
             return message;
             //i want use this return value in old promise chain
          });
    })
};

我还会在代码中更改其他一些内容,因为看起来上面的所有内容都可以简化为:

var func2 = function () {
    someFuncSync();
    return func1();
};

这允许你这样做:

func2().then(function(message) {
    // process message here
}, function(err) {
    // process err here
});

变更摘要:

  1. 如果它始终是同步的,则无需将someFuncSync()包含在promise中。你可以打电话给它然后开始你的承诺链。
  2. 由于标准承诺只返回一个值(不是(message, error)之类的值,因此实际上没有理由在其中使用return message进行回调。您可以直接返回承诺。
  3. return前添加了func1(),因此我们将返回承诺。

答案 1 :(得分:1)

男人,其中一些答案实在是在过度思考。承诺之美是他们的简单:

return func1().then(func2)

答案 2 :(得分:0)

我会通过向旧的承诺链添加一个额外的步骤来实现。

这假设您不需要使用旧承诺链中解析的值。

var func1 = function(){
  return new promise(function(resolve, reject){
    //some operations here
  });
};

var func2 = function(){
  promise.resolve(someFuncSync())
    .then(function(arg){

        return promise.all([
            arg, // Argument that original promise resolved with
            func1() // The new extra promise
        ])
    })
    .spread(function(arg, message){
        // Now i have the new message and also the return value from the old promise.
         console.log(message);
        //printing  func1 returned message in old promise chain
    })
};