[英]What is the best practice for long promise chainings within Promise.All
Suppose I have several main promises, some of which return promise inside.假设我有几个主要的 promise,其中一些在里面返回 promise。 I want to retrieve results from sort of promise functions that why I think about
Promise.all
.我想从某种
Promise.all
函数中检索结果,这就是为什么我会考虑Promise.all
。 First off, let take a look at my example code below首先,让我们看看下面的示例代码
var Promise = require('bluebird');
promise = []
function promise1(){
return new Promise(function(resolve, reject){
console.log('promise1');
resolve('promise1');
});
}
function promise2(){
return new Promise(function(resolve, reject) {
console.log('promise2');
resolve('promise2');
});
}
function promise3(){
promise2().then(function(){
return new Promise(function(resolve, reject) {
console.log('promise3');
resolve('promise3')
})
})
}
Upper piece of code, 2 main promises are promise1
and promise3
.上面一段代码,两个主要的 promise 是
promise1
和promise3
。 promise2
will be returned by promise3
. promise2
将由promise3
返回。 I'm demonstating promise3
as a long promise chaning.我正在
promise3
是一个长期的承诺改变。 To run, I initialized要运行,我初始化
promise = [promise1(), promise3()];
Promise.all(promise).then(function(data){
console.log('done', data);
})
Outcome was结果是
promise1
承诺1
promise2
承诺2
promise3
承诺3
done [ 'promise1', undefined ]
完成 ['promise1',未定义]
but I am expecting that但我期待
done [ 'promise1', 'promise3' ]
完成 ['promise1', 'promise3']
My question is what is the best practice in this case?我的问题是在这种情况下的最佳做法是什么?
promise3
is missing a return
. promise3
缺少return
。 With this it works as expected.有了这个,它可以按预期工作。
function promise3(){
return promise2().then(function(){
// ^^^ missing return here
return new Promise(function(resolve, reject) {
console.log('promise3');
resolve('promise3')
})
})
}
Update:更新:
If you simplify your case you're doing:如果你简化你的案例,你正在做:
var a = new Promise(function(resolve) {
resolve("a");
});
var b = a.then(function () {
return new Promise(function(resolve) {
resolve("b");
}));
});
And then your question is: "why is the resolved value of a
not equal to b
?"然后你的问题是: “为什么
a
的解析值不等于b
?” . . Well, they're two different promises.
嗯,这是两个不同的承诺。
With return a
you return the original promise2
.随着
return a
你返回原来的promise2
。 In a.then
you eventually return promise3
.在
a.then
您最终会返回promise3
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.