Promises
A promise in JavaScript is an eventual completion of an asynchronous operation. A promise is a value that may not be available yet.
No Uncertainty
While a callback may leave us hanging and uncertain about the awaited value, a promise will promise or guarantee a future value and nothing can change it – regardless whether or not the promise is fulfilled or rejected.
Promise States
- Pending (default)
- Fulfilled
- Rejected
How to Work with Promises
1. Create Promise
Create a Promise instance, defining in its constructor the action to execute when promise is fulfilled or rejected using a callback function, called executor.
const examplePromise = new Promise( (resolve, reject) => {
if (conditionSuccess) {
resolve('Successful!');
} else {
reject(Error('Oops..'));
}
});
2. Consume Promise Value
Call PromiseAPI‘s methods (e.g. then
, catch
, etc.) to consume the value or provide a rejection reason in case of an error.
examplePromise
.then( val=>console.log(val) )
.catch( err=>console.log(err) )
.finally( ()=>console.log('All done!') )
then
a method that can be used on a resolved promise.
catch
a method that can be used on a rejected promise.
finally
a method that can be used regardless of the state of the promise.
Example
const order = true;
const breakfastPromise = new Promise( (resolve, reject) => {
setTimeout(() => {
if (order) {
resolve('Your order is ready. Come and get it!');
} else {
reject( Error('Your order cannot be made.') );
}
}, 3000);
});
breakfastPromise
.then( val => console.log(val) )
.catch( err => console.log(err) )
Result will be:
> Promise {<pending>}
> Your order is ready. Come and get it!
Promise.all
The Promise.all()
method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input’s promises have fulfilled, or if the input iterable contains no promises.Sep 13, 2022
Example
Promise.all([
fetchData('https://dog.ceo/api/breeds/list'),
fetchData('https://dog.ceo/api/breeds/image/random')
])
.then(data => {
const breedList = data[0].message;
const randomImage = data[1].message;
generateOptions(breedList);
generateImage(randomImage);
})