Promises and types with examples in details

 

Promises in JavaScript: An Overview

A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises are used to handle asynchronous operations more effectively, enabling cleaner and more manageable code compared to traditional callback-based approaches.

States of a Promise

A Promise can be in one of three states:

  1. Pending: The initial state; the operation is still in progress.
  2. Fulfilled: The operation completed successfully, and the promise has a result.
  3. Rejected: The operation failed, and the promise has a reason (typically an error).

Promise Syntax

js
let promise = new Promise((resolve, reject) => { // asynchronous operation let success = true; if (success) { resolve("Operation successful!"); } else { reject("Operation failed!"); } });

In this example:

  • The promise is created using the new Promise() constructor.
  • The resolve function is called when the asynchronous operation is successful.
  • The reject function is called if there is an error.

Handling Promises with .then(), .catch(), and .finally()

  • .then(onFulfilled, onRejected): This method is used to handle the fulfilled state of a promise. You can also handle rejection by passing an error handler.
  • .catch(onRejected): This method is used to handle the rejected state of a promise.
  • .finally(onFinally): This method runs no matter what (whether the promise is fulfilled or rejected).

Example: Using .then(), .catch(), and .finally()

js
let promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Operation completed successfully!"); } else { reject("Something went wrong!"); } }); promise .then(result => { console.log(result); // "Operation completed successfully!" }) .catch(error => { console.log(error); // "Something went wrong!" }) .finally(() => { console.log("Operation finished (either fulfilled or rejected)."); });

Types of Promises

JavaScript offers a variety of ways to work with Promises, some of the commonly used types and patterns are as follows:


1. Simple Promise Example

A basic example to demonstrate how to create a Promise, resolve it, and handle its result:

js
const myPromise = new Promise((resolve, reject) => { let success = true; // Simulating a success scenario if (success) { resolve("Data received successfully!"); } else { reject("Failed to fetch data."); } }); myPromise .then(response => { console.log(response); // "Data received successfully!" }) .catch(error => { console.error(error); // This will not be called in this case });

2. Promise.all()

Promise.all() takes an array of promises and returns a single promise that resolves when all the promises have been fulfilled. If any of the promises reject, the entire Promise.all() will reject.

Example:

js
const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "First")); const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 2000, "Second")); const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 3000, "Third")); Promise.all([promise1, promise2, promise3]) .then(results => { console.log(results); // ["First", "Second", "Third"] }) .catch(error => { console.error(error); // If any promise is rejected });

Key Points:

  • Promise.all() returns a single promise that resolves when all the promises in the array are fulfilled.
  • If any of the promises reject, Promise.all() rejects immediately with the reason of the first promise that rejects.

3. Promise.race()

Promise.race() takes an array of promises and returns a single promise that resolves or rejects as soon as one of the promises in the array resolves or rejects. Whichever promise is fulfilled or rejected first, the result is passed forward.

Example:

js
const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 1000, "First")); const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 500, "Second")); Promise.race([promise1, promise2]) .then(result => { console.log(result); // "Second" (since it resolves first) }) .catch(error => { console.log(error); // Will not be reached in this case });

Key Points:

  • Promise.race() resolves or rejects based on the first promise to resolve or reject in the array.

4. Promise.allSettled()

Promise.allSettled() returns a promise that resolves once all promises have settled (either fulfilled or rejected), and it provides the outcome of each promise.

Example:

js
const promise1 = Promise.resolve(3); const promise2 = Promise.reject("An error occurred"); const promise3 = Promise.resolve(42); Promise.allSettled([promise1, promise2, promise3]) .then(results => { console.log(results); // [ // { status: "fulfilled", value: 3 }, // { status: "rejected", reason: "An error occurred" }, // { status: "fulfilled", value: 42 } // ] });

Key Points:

  • Unlike Promise.all(), Promise.allSettled() doesn't short-circuit if a promise rejects.
  • It always resolves once all promises have settled, returning an array of objects with each promise's status and result.

5. Promise.any()

Promise.any() returns a promise that resolves as soon as any of the promises in the array resolves. If all promises reject, it will reject with an AggregateError.

Example:

js
const promise1 = Promise.reject("Error 1"); const promise2 = Promise.reject("Error 2"); const promise3 = Promise.resolve("Success!"); Promise.any([promise1, promise2, promise3]) .then(result => { console.log(result); // "Success!" }) .catch(error => { console.log(error); // Will not be called in this case });

Key Points:

  • Promise.any() resolves as soon as any promise in the array fulfills, and it rejects only if all promises reject.
  • The rejection reason will be an AggregateError when all promises fail.

6. Chaining Promises

One of the core features of promises is the ability to chain multiple .then() calls. Each .then() returns a new promise, allowing for asynchronous operations to be performed sequentially.

Example:

js
const promise = new Promise((resolve, reject) => { setTimeout(() => resolve(5), 1000); // Resolves with value 5 after 1 second }); promise .then(result => { console.log(result); // 5 return result * 2; // Returning a new value }) .then(result => { console.log(result); // 10 return result + 3; }) .then(result => { console.log(result); // 13 }) .catch(error => { console.error(error); // Handle any errors that occur in the chain });

Key Points:

  • Each .then() handles the resolved value from the previous .then() and can return a new value or another promise.
  • .catch() can be used at the end of a chain to catch any errors that occur anywhere in the chain.

7. Handling Async Functions with Promises

JavaScript’s async/await syntax allows working with promises in a more synchronous-like manner. The await keyword can be used to wait for a promise to resolve, making it easier to write asynchronous code without using .then() and .catch().

Example:

js
async function fetchData() { const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Data fetched!"), 1000); }); try { const result = await promise; console.log(result); // "Data fetched!" } catch (error) { console.error(error); // Will not be reached in this case } } fetchData();

Key Points:

  • async functions always return a promise, and await is used to wait for the promise to resolve.
  • Errors can be caught using try/catch blocks inside async functions.

Conclusion:

  • Promises in JavaScript help handle asynchronous operations in a more manageable way than using callbacks.
  • Types of Promises like Promise.all(), Promise.race(), Promise.allSettled(), and Promise.any() offer different ways to handle multiple promises simultaneously, each suited to different use cases.
  • Chaining promises allows asynchronous operations to be performed in a sequence, while async/await syntax simplifies handling promises in a more synchronous style.

By understanding these types of promises and their behaviors, you can efficiently handle asynchronous logic in JavaScript applications.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

oAuth in angular