return makeFirstPromise()
.then(function(res1) {
(...)
})
.then(function(res2) {
(...)
})
.then(function(res3) {
// **here I need to access res1**
});
我想知道当我需要访问 promise 链的后续函数中的先前 promise 结果时是否有最佳实践。
我看到两种可能的解决方案:
var r1;
return makeFirstPromise()
.then(function(res1) {
r1 = res1;
(...)
})
.then(function(res2) {
(...)
})
.then(function(res3) {
console.log(r1);
});
或者将 promise 嵌套在第一个 promise 之后,但它在视觉上破坏了链顺序:
return makeFirstPromise()
.then(function(res1) {
(...)
return secondPromise(res2)
.then(function(res3) {
console.log(res1);
});
});
有什么想法吗?
最佳答案
Promise 语法被设想为 be used in the first way 。第二种语法很快就会变得困惑。
但不要忘记将结果传递到下一个 Promise 中。
var r1;
return makeFirstPromise()
.then(function(res1) {
r1 = res1;
(...)
return r1;
})
.then(function(r1) {
(...)
});
关于javascript - JavaScript Promise 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27319781/