如何将承诺join承诺链

我有func1函数返回一个promise。 在func2我已经开始承诺链。 我想在这里做的是,我想在旧诺言链中使用func1parsing消息,我想这个代码是不那么复杂。 joinfunc1的最好方法是在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 }) }; 

男人,这些答案中的一些真的是过度的东西。 许诺的美丽是他们的简单:

 return func1().then(func2) 

只需从.then()处理程序中返回新的promise,它就会自动添加到前一个链中,然后控制旧promise链的parsing值。

外部的承诺不会解决,直到新的承诺解决,内在的承诺将控制最终解决的价值。 我在你的调用前面添加了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)那样的东西(message, error) ,所以没有任何callbackreturn message原因,你可以直接返回promise。
  3. func1()前添加return ,所以我们返回promise。

我会通过向旧承诺链添加一个额外的步骤来做到这一点。

这假定您不需要使用新旧承诺链中parsing的值。

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