Suppose I have several main promises, some of which return promise inside. I want to retrieve results from sort of promise functions that why I think about 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
. promise2
will be returned by promise3
. I'm demonstating promise3
as a long promise chaning. To run, I initialized
promise = [promise1(), promise3()];
Promise.all(promise).then(function(data){
console.log('done', data);
})
Outcome was
promise1
promise2
promise3
done [ 'promise1', undefined ]
but I am expecting that
done [ 'promise1', 'promise3' ]
My question is what is the best practice in this case?
promise3
is missing a 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
?". Well, they're two different promises.
With return a
you return the original promise2
. In a.then
you eventually return promise3
.