I want to execute my code in the following order:
I'm having some trouble figuring it out, my code so far is below.
function getPromise1() {
return new Promise((resolve, reject) => {
// do something async
resolve('myResult');
});
}
function getPromise2() {
return new Promise((resolve, reject) => {
// do something async
resolve('myResult');
});
}
function getPromise3() {
return new Promise((resolve, reject) => {
// do something async
resolve('myResult');
});
}
getPromise1()
.then(
Promise.all([getPromise2(), getPromise3()])
.then() // ???
)
.then(() => console.log('Finished!'));
Approach 1: In this approach, we will use Promise. all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.
Introduction to the JavaScript promise chaining The callback passed to the then() method executes once the promise is resolved. In the callback, we show the result of the promise and return a new value multiplied by two ( result*2 ).
Here, Promise. all() method is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.
As stated in the comments promises cannot be canceled.
Just return Promise.all(...
getPromise1().then(() => {
return Promise.all([getPromise2(), getPromise3()]);
}).then((args) => console.log(args)); // result from 2 and 3
I know it's an old thread, but isn't
() => {return Promise.all([getPromise2(), getPromise3()]);}
a little superfluous? The idea of fat arrow is that you can write it as:
() => Promise.all([getPromise2(), getPromise3()])
which makes the resulting code somewhat clearer:
getPromise1().then(() => Promise.all([getPromise2(), getPromise3()]))
.then((args) => console.log(args)); // result from 2 and 3
Anyway, thanks for the answer, I was stuck with this :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With