Promise in JavaScript

Promise in JavaScript

Asynchronous programming is a fundamental aspect of modern web development. In JavaScript, promises provide an elegant way of handling asynchronous operations. Promise chaining is a technique that allows you to perform a series of asynchronous operations in a sequence. In this article, we will explore promise chaining in JavaScript and how to handle multiple promises.

What are Promises

Promises are a powerful tool in JavaScript for handling asynchronous operations. A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value.

Creating a Promise

A Promise can be created using the Promise constructor. The constructor takes a function called the executor function that takes two arguments, resolve and reject. Resolve is a function that is called when the operation is successful, and reject is a function that is called when the operation fails.

const promise = new Promise((resolve, reject) => {
? // Perform some asynchronous operation
? const result = Math.random();
? if (result > 0.5) {
? ? resolve(result);
? } else {
? ? reject('Error');
? }
});        

In this example, we create a new Promise and pass an executor function as an argument. Inside the executor function, we perform some asynchronous operation and randomly resolve or reject the promise.

Promise States

A Promise can be in one of three states: pending, fulfilled, or rejected. When a Promise is created, it is in the pending state. If the asynchronous operation is successful, the Promise transitions to the fulfilled state, and the result is available. If the asynchronous operation fails, the Promise transitions to the rejected state, and an error is available.


const promise = new Promise((resolve, reject) => {
? // Perform some asynchronous operation
? const result = Math.random();
? if (result > 0.5) {
? ? resolve(result);
? } else {
? ? reject('Error');
? }
});


promise
? .then((result) => {
? ? console.log(result); // result is available in the fulfilled state
? })
? .catch((error) => {
? ? console.error(error); // error is available in the rejected state
? });        

In this example, we create a Promise and then use the then() method to handle the fulfillment of the Promise and the catch() method to handle the rejection of the Promise.

Chaining Promises

Promises can also be chained together. When a Promise is fulfilled, it can return a new Promise that can be further handled with then() and catch() methods. This is known as Promise chaining.

const promise = new Promise((resolve, reject) => {
? // Perform some asynchronous operation
? const result = Math.random();
? if (result > 0.5) {
? ? resolve(result);
? } else {
? ? reject('Error');
? }
});

promise
? .then((result) => {
? ? console.log(result);
? ? return result * 2;
? })
? .then((result) => {
? ? console.log(result);
? })
? .catch((error) => {
? ? console.error(error);
? });        

In this example, we create a Promise and use the then() method to handle its fulfillment. Inside the first then() method, we log the result and then return a new Promise that multiplies the result by 2. The second then() method is used to handle the fulfillment of this new Promise.

Handling Multiple Promises

Handling multiple Promises in JavaScript is a common task when dealing with asynchronous operations. There are several ways to handle multiple Promises, including using the Promise.all(), Promise.allSettled(), and Promise.race() methods.

Promise.all()

The Promise.all() method is used to execute multiple Promises in parallel and wait for all of them to complete. It takes an array of Promises as an argument and returns a new Promise that resolves to an array of the results of each Promise.

const promise1 = new Promise((resolve, reject) => {
? setTimeout(() => {
? ? resolve('Promise 1 resolved');
? }, 2000);
});


const promise2 = new Promise((resolve, reject) => {
? setTimeout(() => {
? ? resolve('Promise 2 resolved');
? }, 1000);
});


Promise.all([promise1, promise2])
? .then((results) => {
? ? console.log(results); // ['Promise 1 resolved', 'Promise 2 resolved']
? })
? .catch((error) => {
? ? console.error(error);
? });        

In this example, we create two Promises that resolve after different periods of time. We then pass an array of these Promises to Promise.all() and use the then() method to handle the results. The results are returned as an array in the same order as the Promises were passed.

If any of the Promises in the array reject, the Promise returned by Promise.all() will immediately reject with the reason of the first Promise that was rejected.

Promise.allSettled()

The Promise.allSettled() method is similar to Promise.all() in that it executes multiple Promises in parallel. However, it does not immediately reject if one of the Promises rejects. Instead, it waits for all Promises to settle (either resolve or reject) and returns an array of objects that describe the outcome of each Promise.

const promise1 = new Promise((resolve, reject) => {
? setTimeout(() => {
? ? resolve('Promise 1 resolved');
? }, 2000);
});


const promise2 = new Promise((resolve, reject) => {
? setTimeout(() => {
? ? reject('Promise 2 rejected');
? }, 1000);
});


Promise.allSettled([promise1, promise2])
? .then((results) => {
? ? console.log(results);
? ? /*
? ? ? [
? ? ? ? { status: 'fulfilled', value: 'Promise 1 resolved' },
? ? ? ? { status: 'rejected', reason: 'Promise 2 rejected' }
? ? ? ]
? ? */
? });        

In this example, we create two Promises that resolve and reject after different periods of time. We then pass an array of these Promises to Promise.allSettled() and use the then() method to handle the results. The results are returned as an array of objects, each describing the outcome of a Promise.

Promise.race()

The Promise.race() method is used to execute multiple Promises in parallel and return the result of the first Promise that resolves or rejects. It takes an array of Promises as an argument and returns a new Promise that resolves or rejects as soon as one of the Promises in the array resolves or rejects.


const promise1 = new Promise((resolve, reject) => {
? setTimeout(() => {
? ? resolve('Promise 1 resolved');
? }, 2000);
});


const promise2 = new Promise((resolve, reject) => {
? setTimeout(() => {
? ? resolve('Promise 2 resolved');
? }, 1000);
});


Promise.race([promise1, promise2])
? .then((result) => {
? ? console.log(result); // 'Promise 2 resolved'
? })
? .catch((error) => {
? ? console.error(error);
? });        

In this example, we create two Promises that resolve after different periods of time. We then pass an array of these Promises to Promise.race() and use the then() method to handle the result. Since promise2 resolves before promise1, the result returned by Promise.race() will be the resolved value of promise2, which is 'Promise 2 resolved'.

If any of the Promises in the array reject, the Promise returned by Promise.race() will immediately reject with the reason of the first Promise that was rejected.

Promise.race() can be useful when you have multiple Promises that perform the same operation, and you want to use the result of the first one that completes. It can also be used when you have multiple APIs that can provide the same data, and you want to use the result from the fastest one.

Conclusion

In this article, we explored how to handle multiple Promises in JavaScript using the Promise.all(), Promise.allSettled(), and Promise.race() methods. Each method has its own unique way of handling multiple Promises and can be used in different scenarios.

Promise.all() is used when you want to execute multiple Promises in parallel and wait for all of them to complete. Promise.allSettled() is similar to Promise.all(), but it does not immediately reject if one of the Promises rejects. Instead, it waits for all Promises to settle and returns an array of objects that describe the outcome of each Promise. Promise.race() is used when you want to execute multiple Promises in parallel and return the result of the first Promise that resolves or rejects.

By understanding these methods and how to use them, you can effectively handle multiple Promises in your JavaScript applications and improve their performance and efficiency.

#JavaScript #Promises #PromiseAll #PromiseAllSettled #PromiseRace #AsyncProgramming #WebDevelopment #SoftwareDevelopment #Coding #Programming #somethingdifferent

要查看或添加评论,请登录

社区洞察

其他会员也浏览了