It is quite common during web development that we run across scenarios where we have to orchestrate different asynchronous operations together. This blog describes ways in which we can combine Promises, our default async operation strategy and their applications.
You can create a promise with: You can get result of a promise with: A Promise is also a guarantee of an asychronous operation, any operation that is wrapped in a Promise will only be resolved or rejected only by the next clock tick.Promise
An object representing the eventual completion (or failure) of an asynchronous operation, and its resulting value.const promise = new Promise((resolveCallback, rejectCallback) => {
// Operation
});
promise.then(
(resolvedResult) => {
// This function is called if promise is resolved.
},
(rejectionReason) => {
// This function is called if promise is rejected.
},
);
A promise can be of three different states:
A promise that is either Fulfilled or Rejected is said to be settled.
All of the combinators take an array of Promises as argument.
This is the most widely used among the combinators. Here is how we can use it:
Promise.all([promiseA, promiseB]).then(
([promiseAResponse, promiseBResponse]) => {
// Do something with it here
},
);
Promise.all
is fulfilled if all promises that are provided to it are fulfilled or if one of the promises is rejected.
Promise.race([promiseA, promiseB]).then(
([promiseAResponse, promiseBResponse]) => {
// Do something with it here
},
);
Promise.race
is fulfilled when one of the promises is settled (fulfilled or rejected).
Promise.allSettled([promiseA, promiseB]).then(
([promiseAResponse, promiseBResponse]) => {
// Do something with it here
},
);
Returns when all promises are settled (fulfilled or rejected).