2014-12-05 41 views
2
return makeFirstPromise() 
    .then(function(res1) { 
     (...) 
    }) 
    .then(function(res2) { 
     (...) 
    }) 
    .then(function(res3) { 
     // **here I need to access res1** 
    }); 

我想知道当我需要访问前一个承诺时,是否有最佳做法导致我的承诺链的后续功能。关于JavaScript Promise的最佳做法

我看到了两个可能的解决方案:

var r1; 
return makeFirstPromise() 
    .then(function(res1) { 
     r1 = res1; 
     (...) 
    }) 
    .then(function(res2) { 
     (...) 
    }) 
    .then(function(res3) { 
     console.log(r1); 
    }); 

或窝后的第一个承诺,但它在视觉上打破了链序列:

return makeFirstPromise() 
    .then(function(res1) { 
     (...) 
     return secondPromise(res2) 
      .then(function(res3) { 
       console.log(res1); 
      }); 
    }); 

任何想法?

+0

的[?如何访问的。那么()链先前承诺的结果(精确复制http://stackoverflow.com/questions/28250680/how-do-i -access-previous-promise-results-in-a-then-chain) – Bergi 2015-01-31 10:58:08

回答

3

Promise语法构想为be used in the first way。第二种语法非常快速地混淆。
但不要忘记将结果传递给下一个承诺。

var r1; 
return makeFirstPromise() 
    .then(function(res1) { 
     r1 = res1; 
     (...) 
     return r1; 
    }) 
    .then(function(r1) { 
     (...) 
    }); 
+0

问题是我的第二个承诺已经返回一个值(res2)。 – Guid 2014-12-05 16:08:31

+0

从结果中创建一个数组''''或对象'{}'。 – Clawish 2014-12-05 16:10:28

+1

如果我不控制第二个承诺(如nodejs函数),可能会导致复杂的代码,但我更喜欢这个解决方案,而不是变量声明解决方案。谢谢。 – Guid 2014-12-05 16:14:43

2

概念上承诺代理值,最简单的方式使用它们的值是使用它们作为代理。这是他们摘要:

var res1 = makeFirstPromise(); 
var res2 = res1.then(makeSecondPromise); 
Promise.all([res1, res2]).spread(function(firstResult, secondResult){ 
    // access both here, no nesting or closure hacks required. 
}); 
+0

不错的想法,但我有一个承诺链,它可能是第七,需要从第三个承诺的结果,例如。 – Guid 2014-12-06 13:27:04

+0

为什么这么重要?还要注意,像Bluebird这样的一些承诺实现有一个你可以传递的上下文 - 看看蓝鸟API的Promise#bind - 也可以解决你的问题。 – 2014-12-06 13:33:40