JavaScript, known for its asynchronous capabilities, revolutionized with the introduction of Promises. A clear way to deal with asynchronous operations without sinking in the callback hell, Promises pave the way for more readable and maintainable code. Let’s dive deep into the world of Promises!
Contents
The Essence of Promises
A Promise in JavaScript represents a value which might be available now, or in the future, or never. It provides a mechanism to handle the eventual result or failure of asynchronous operations.
Promise.resolve()
The resolve function within the promise constructor are used to fulfill the promise’s eventual result. This is called when the code inside promise is successful executed.
const jottup = Promise.resolve("Resolved Value"); jottup.then(value => console.log(value)); // "Resolved Value"
Promise.reject()
The reject function within the promise constructor are used to reject the promise’s eventual result. The reject function is called when it encounters an error.
const jottup = Promise.reject("Reason for Rejection"); jottup.catch(reason =>; console.log(reason)); // "Reason for Rejection"
Promise.then()
Handling Promise Results. The `then` method returns a new Promise. It takes up to two arguments: callback functions for success and failure cases.
const jottup = new Promise((resolve, reject) => { resolve("Success!"); }); jottup.then( result => console.log(result), // "Success!" error => console.log(error) );
Promise.catch()
Handling Promise Error. The method `catch` returns a Promise only in case when we have error in promise execution process. It behaves the same as calling `Promise.then(undefined, onRejected)`.
const jottup = new Promise((resolve, reject) => { reject("Error!"); }); jottup.catch(error => console.log(error)); // "Error!"
Promise.finally()
Cleanup Operations. The `finally` method lets you execute a callback once the Promise is settled, regardless of its outcome.
const jottup = new Promise((resolve, reject) => { resolve("Success!"); }); jottup.finally(() => console.log("Promise settled!")) .then(result => console.log(result)); // "Promise settled!" followed by "Success!"
Promise.all()
Handling Multiple Promises. This method returns a new Promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.
const jottup1 = Promise.resolve("First"); const jottup2 = Promise.resolve("Second"); Promise.all([jottup1, jottup2]) .then([jottupresult1, jottupresult2] => console.log('all promises done')) // ["First", "Second"] .catch(e => console.log('error')); // here will error from first failed promise
Promise.race()
The First to Resolve. The `race` method takes an array of promises and returns a new promise which is settled in the same way as the first passed promise to settle. It resolves or rejects, with the value or reason from that promise. Another words it return a new promise when first of promises from array will be resolved or rejected
const jottup1 = new Promise((resolve, reject) => { setTimeout(resolve, 500, "First"); }); const jottup2 = new Promise((resolve, reject) => { setTimeout(resolve, 100, "Second"); }); Promise.race([jottup1, jottup2]).then(value => console.log(value)); // "Second"
Promise.allSettled()
The allSettled
method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that describe the outcomes.
Why use it? This method is especially useful when you need to know the outcome of multiple promises, even if some fail.
let jottup1 = Promise.resolve(2); let jottup2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'some error')); Promise.allSettled([jottup1, jottup2]]).then(data => console.log(data)); // Output: [{status: "fulfilled", value: 2}, {status: "rejected", reason: "some error"}]
Promise.any()
The any
method returns a promise that is fulfilled by the first given promise to be fulfilled or rejected with an AggregateError if all the given promises are rejected.
Why use it? This is useful when you need a response from any of the multiple requests and don’t require all of them to complete.
let jottup1 = new Promise((resolve, reject) => setTimeout(reject, 200, 'jottup one')); let jottup2 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'jottup two')); Promise.any([jottup1, jottup2]]).then(value => console.log(value));// Output: 'jottup two'
Summary
Understanding Promises and their methods is fundamental for modern JavaScript development. They simplify asynchronous operations, making your code cleaner and easier to follow. Remember, the strength of your code lies in its clarity, maintainability, and efficiency, and Promises play a big role in achieving that!