Reputation: 25
I have the following code
var pOne = new Promise(function(callback){
setTimeout(function(){
callback(false);
}, 100);
}).then(function(v){
console.log("pOne: " + v);
});
var pTwo = new Promise(function(callback){
setTimeout(function(){
callback(true);
}, 100);
}).then(function(v){
console.log("pTwo: " + v);
});
Promise.all([pOne, pTwo]).then(function(values){
console.log(values);
});
The console.log(values)
displays [undefined, undefined]
in the console. My understanding of promises is that I should be able to chain the then()
method. Does chaining not work with the Promise.all()
or is this a bug.
Note: I am using the promise-polyfill but running it on chrome, so it technically it is using native chrome implementation of promises.
Upvotes: 0
Views: 3509
Reputation: 2865
pOne
and pTwo
have to resolve with a value in order for that value to be passed to the result of Promise.all
.
var pOne = new Promise(function(callback){
setTimeout(function(){
callback(false);
}, 100);
}).then(function(v){
console.log("pOne: " + v);
return v;
});
Notice the return v
inside of the .then
callback. That means that the pOne
promise is going to resolve with that value (v
in this case being whatever the previous Promise resolved with, or in this case, false
.
Now do the same for the pTwo
promise.
var pTwo = new Promise(function(callback){
setTimeout(function(){
callback(true);
}, 100);
}).then(function(v){
console.log("pTwo: " + v);
return v;
});
Again, we have to return a value from the .then
callback function in order for the Promise to resolve with a value, rather than with undefined.
Now, Promise.all
is going to run the Promises, and when (or if) they resolve (in our case they always do), it's going to get the resolved value from each one, and the Promise.all
promise itself is going to resolve with the values.
Upvotes: 2
Reputation: 6251
your pOne and pTwo promises don't return anything.
Try this:
var pOne = new Promise(function(callback){
setTimeout(callback, 100, true);
}).then(function(v){
return v;
});
var pTwo = new Promise(function(callback){
setTimeout(callback, 100, false);
}).then(function(v){
return v;
});
Promise.all([pOne, pTwo]).then(function(values){
console.log(values);
});
Upvotes: 3