2016-04-30 95 views
1

我有func1函数返回承诺。在func2我已经开始承诺链。 我想在这里做的是,我想在旧承诺链中使用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 
    }) 
}; 
+0

你不能做到这一点,你可以访问只在'then' func1中发送消息。 – Grundy

+0

@JonathanLonowski你应该发布它作为答案。只需使用'then(function(message){console.log(message)})'。 – dfsq

+0

“链”是什么意思?序列?你想分别用func1和func2的解析值做什么? –

回答

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 
    }) 
}; 
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()成承诺,如果它总是同步的。你可以打电话给它,然后开始你的承诺链。
  2. 由于标准的承诺,只返回一个值(不是像(message, error),实在没有理由在这return message回调。您只需直接返回的承诺。
  3. 新增returnfunc1()前面,所以我们正在回归。承诺
+0

@ doug65536 - 作品这里非常好:https://jsfiddle.net/jfriend00/pxbLvz2w/ – jfriend00

+0

是的,你说得对。如果在该行上有'return'后没有更多的文本,'return'将只是一个可能的ASI问题。 – doug65536

+0

就个人而言,我始终把第一'。那么()'在同一行上一个函数调用,因为我认为,阅读更清晰,有更多的惊喜 - 这个特殊的方案是使用OP这里发生了什么。 – jfriend00

1

人,有些答案真的东西得太多承诺的优点是其简单:

return func1().then(func2)