I'm trying to grok how Promise.all works, and it seems like it ought to be simple. My understanding is that Promise.all takes an array of promises and then executes them all at the same time.
Here's some code I wrote that I execute via node (8.10.0) that I expected would work properly:
const getFirstPromise = function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("1");
resolve("First!"); // Yay! Everything went well!
}, 2500);
});
};
const getSecondPromise = function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("2");
resolve("Second!"); // Yay! Everything went well!
}, 250);
});
};
const getThirdPromise = function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("3");
resolve("Third!"); // Yay! Everything went well!
}, 1000);
});
};
const getFourthPromise = function () {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("4");
resolve("Fourth!"); // Yay! Everything went well!
}, 500);
});
};
const tasks = [
getFirstPromise,
getSecondPromise,
getThirdPromise,
getFourthPromise
];
Promise.all(tasks).then((result) => console.log("Done alling the promises: ", result)).catch(err => console.log(err));
As written, this doesn't execute any of the promises.
If I change the tasks collection to look like this:
const tasks = [
getFirstPromise(),
getSecondPromise(),
getThirdPromise(),
getFourthPromise()
];
then all of the promises execute, but if I comment out the Promise.all line, they still execute.
What I was expecting was to create a collection of promises that would NOT be run until Promise.all was called.
Please either explain how to achieve what I'm expecting OR explain how my understanding of Promise.all is flawed or tell me how else I should be creating my promises.
I'm not interested in the myriad of other ways of executing this series of promises. I just want to understand how Promise.all should work with a collection of promises in the case where I don't want the promise code to run until Promise.all is executed.