
A promise is an object which either gives you a result or error in the future as soon as it completes the task. It is a popular design pattern used to handle asynchronous tasks in Node.js. It can take care of parallel/serial execution of many tasks along with their chaining rules. The promise structure also provides effective error-catching mechanisms.
Promise.resolve():
The Promise.resolve() method returns a resolved Promise object with a given value. Depending upon a resolved promise value,
1. returns promise if fulfilled with promise
2. returns a value if fulfilled with the value
3. returns thenable promise by adopting its eventual state if fulfilled with thenable promise
This function flattens nested layers of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer.
Promise.resolve('Success').then((value) => {
console.log(value); // "Success"
}).catch((error) => {
console.log(error);
});
Promise.reject():
Promise.reject() method returns a Promise object that is rejected with a given reason.
Promise.reject('failure')
.then((value) => {
console.log(value);
}).catch((error) => {
console.log(error); // "failure"
});
Promise.then():
The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise
.
const promise1 = new Promise((resolve, reject) => {
resolve('Success!');
});
promise1.then((value) => {
console.log(value);
// expected output: "Success!"
}, (error) => {
console.log( error);
});
Promise.catch():
The catch() method returns a rejected Promise. It behaves the same as calling Promise.prototype.then(undefined, onRejected). Calling Promise.catch(onRejected) internally calls Promise.then(undefined, onRejected).
const promise1 = new Promise((resolve, reject) => {
throw 'Exception handling';
});
promise1.then((value) => {
console.log(value);
}).catch((error) => {
console.error(error);
});
> "Exception handling"
Promise.finally():
The finally() method returns a Promise. When the promise is settled, the specified callback function is executed. This provides a way for code to be run irrespective of promise settlement. A finally callback will not receive any argument, since there is no way of determining if the promise was fulfilled or rejected.
const promise1 = Promise.reject("Rejecting Promise");
promise1
.then(value => {
console.log(value)
})
.catch(err => {
console.log(err)
})
.finally(() => {
console.log("completed promise")
});
> "Rejecting Promise"
> "completed promise"
Common Promise utility methods:
Promise.all():
Promise.all() method takes an array of promises and returns a single promise, which is either resolved or rejected based on any iterable promise. It resolves if all the promises inside the array resolve and reject if any of the promises reject.
const promise1 = Promise.resolve("hello world");
const promise2 = "Promise 2";
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values);
});
// expected output: Array ["hello world", "Promise 2", "foo"]
Promise.race():
Promise.race() method also takes an array of promises and return a single promise, which is either resolved or rejected based on an array of iterable promise. Unlike promise.all() it will not wait till all the promise executes. It will return the promise as soon as any of the promises is either resolve or reject.
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 300, 'Hello world');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'Goodbye world');
});
Promise.race([promise1, promise2]).then((value) => {
console.log(value);
// Both resolve, but promise2 is faster
});
> "Goodbye world"
Promise.any():
Promise.any() method takes an array of promises and returns a single promise. It will resolve if any of the promises in an array is resolved with the resolved value, and if all the promises are rejected promise will be rejected with the error “AggregateError: All promises were rejected”. AggregateError
, a new subclass of Error
that groups together individual errors.
const promise1 = Promise.reject(0);
const promise2 = Promise.resolve('Hello world');
const promise3 = new Promise((resolve) => setTimeout(resolve, 300, 'Good bye'));
const promises = [promise1, promise2, promise3];
Promise.any(promises).then((value) => console.log(value));
> Hello world
Promise.allSettled():
Promise.allSettled() method takes an array of promises and returns a single promise. This is typically used when promises inside an array are independent of each other and rejection of one promise should not stop the other promise. The main difference between Promise.all() and Promise.allSettled() is that prior stops the execution of any of the promises rejects and mostly used in a case where promises are dependent on each other whereas following will wait until all the promises are settled and give the result in array form.
const promise1 = Promise.resolve("Hello world");
const promise2 = Promise.reject('Rejecting');;
const promises = [promise1, promise2];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result)));
> Object { status: "fulfilled", value: "Hello world" }
> Object { status: "rejected", reason: "Rejecting" }
In an upcoming post, we will look at async/await, which is more syntactical sugar on top of promises that can radically simplify code, add readability, & significantly reducing lines of code.
Thanks for reading.
To the noob2geek.in owner, Your posts are always well written.
Hi noob2geek.in admin, Your posts are always well-cited and reliable.
Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!
Hi noob2geek.in admin, Good to see your posts!
Dear noob2geek.in webmaster, Your posts are always well-delivered and engaging.
Hi noob2geek.in webmaster, You always provide great examples and case studies.
Hi noob2geek.in admin, Good to see your posts!
Hello noob2geek.in administrator, Your posts are always well-received and appreciated.
Hello noob2geek.in webmaster, Your posts are always well-referenced and credible.
Hello noob2geek.in admin, Thanks for the well-organized and comprehensive post!
Hello noob2geek.in owner, Thanks for the well-organized and comprehensive post!
To the noob2geek.in owner, Keep sharing your knowledge!
To the noob2geek.in administrator, Thanks for the well-structured and well-presented post!
Dear noob2geek.in admin, Good to see your posts!
Dear noob2geek.in owner, Your posts are always well-balanced and objective.
Hello noob2geek.in webmaster, Your posts are always a great source of information.
Hello noob2geek.in webmaster, Your posts are always well structured and easy to follow.
Dear noob2geek.in webmaster, You always provide helpful information.
Dear noob2geek.in owner, Great content!
To the noob2geek.in owner, Your posts are always interesting.
To the noob2geek.in owner, Well done!
Hi noob2geek.in webmaster, Your posts are always a great read.
Dear noob2geek.in owner, Your posts are always informative and well-explained.
Pingback: 13 Basic but Important JavaScript Interview Questions | Noob2Geek
Thanks for writing this in simplest way. It helped me to clear up doubts between all settled and all method.