JavaScript promises for absolute beginners
In layman’s term, A Promise is a piece of JavaScript code that represents a completion or failure of an asynchronous operation and its resulting value.
Eg:
let myPromise = aPromiseFunction();
Here aPromiseFunction
is a Promise object which can return a value at a later point of time which can be either a success or failure.So till that time it acts as a Proxy (A nominee for some other value).
Structure of a Promise
let myPromise = new Promise(function(resolveFunction, rejectFunction) {
resolveFunction(); // when successful
rejectFunction(); // when error
});
And then we can consume the promise like this
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Here resolveFunction
and rejectFunction
represents the callbacks corresponding to success and error and it can take payloads correspondingly.
Lets restructure our Promise
let myPromise = new Promise(function(resolveFunction, rejectFunction) {
if(someBusinessConditionisTrue()) {
resolveFunction("OK"); // when successful
}else{
rejectFunction("ERROR"); // when error
}
});
Here someBusinessConditionisTrue
is some function that returns true or false in our code.
And now the consuming part becomes
myPromise.then(
function(value) { console.log(value); }, /* OK */
function(error) { console.log(error); } /* ERROR */
);
How to use promise for an async operation
I have hosted one API at https://615fcf10f7254d001706821b.mockapi.io/api/v1/users
which return an array of user data objects for this example.Let’s use Fetch
for async calls.
let userPromise= new Promise(function(resolveFunction, rejectFunction) {
console.log('Promise Initializing');
fetch('https://615fcf10f7254d001706821b.mockapi.io/api/v1/users')
.then(response => response.json())
.then(data => resolveFunction(data))
.catch((error) => {
rejectFunction(error);
});
});
And at the consuming part
userPromise.then(
function(value) {console.log(value);},
function(error) {console.log(error);}
).finally(function(data) { /* This part will always execute either for success or error */
console.log('Promise executed successfully');
});
The output console
Promise methods
Lets consider the following , we have three promises.
let promise1 = Promise.resolve('Hello');
let promise2 = Promise.reject('Reject');
let promise3= new Promise(function(resolveFunction, rejectFunction) {
console.log('Promise Initializing');
fetch('https://615fcf10f7254d001706821b.mockapi.io/api/v1/users')
.then(response => response.json())
.then(data => resolveFunction(data))
.catch((error) => {
rejectFunction(error);
});
});
Now lets create the promise methods
1.Promise.all
Promise.all([promise1, promise2, promise3]).then(values => {
console.log(values);
}).catch(d => {
console.log(d);
});
Here Promise.all takes an iterable list of promise data and returns a single promise that resolves to an array of the input promises.It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.In the example promise2
is a rejected one so it will be captured in the catch block.And the output will be Reject. and if suppose promise2
returns as a resolved one like
let promise2 = Promise.resolve('Dont reject');
then the output will be :
2.Promise.race
The Promise.race
method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise.
Lets modify our promises a little bit
let promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'Hello');
});
let promise2 = Promise.resolve('Dont reject');
let promise3= new Promise(function(resolveFunction, rejectFunction) {
console.log('Promise Initializing');
fetch('https://615fcf10f7254d001706821b.mockapi.io/api/v1/users')
.then(response => response.json())
.then(data => resolveFunction(data))
.catch((error) => {
rejectFunction(error);
});
});
Promise.race([promise1, promise2, promise3]).then(values => {
console.log(values);
}).catch(values => {
console.log(values);
});
The output will be promise2 (Dont reject
)as it will be resolving or rejecting faster than the other two:
3.Promise.any
Promise.any
takes an iterable of the Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.
Our previous example with some changes to promise1
and promise 2
let promise1 = Promise.reject('Reject 1');
let promise2 = Promise.resolve('Resolve 2');
let promise3= new Promise(function(resolveFunction, rejectFunction) {
console.log('Promise Initializing');
fetch('https://615fcf10f7254d001706821b.mockapi.io/api/v1/users')
.then(response => response.json())
.then(data => resolveFunction(data))
.catch((error) => {
rejectFunction(error);
});
});Promise.any([promise1, promise2, promise3]).then(values => {
console.log(values);
}).catch(values => {
console.log(values);
});
The output will be promise2 (Resolve 2)
as promise1
is a rejected one and promise3
is yet to fulfill.
4.Promise.allSettled
The Promise.allSettled()
method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
Promise.allSettled([promise1, promise2, promise3]).then(values => {
console.log(values);
}).catch(values => {
console.log(values);
});
And the output will be :
Conclusion
We have gone through the basics of a Promise, its constructor ,object and the most important methods available with it.
Ill be publishing the same for Observables also :)
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise