javascript promise all | chain | race | async await

JavaScript Promises are a powerful and flexible way to handle asynchronous operations. They provide a more structured and readable way to work with asynchronous code compared to callbacks. Let's delve into the key concepts of JavaScript Promises:

javascript promise


1. Asynchronous Operations:

  • Promises are commonly used to manage asynchronous operations, such as fetching data from a server, reading a file, or executing code after a timeout.
  • Asynchronous operations in JavaScript typically involve callbacks, but Promises offer a more organized and readable approach.


2. Promise States:

 A Promise can be in one of three states:

  • Pending: The initial state, before the promise is resolved or rejected.
  • Fulfilled (Resolved):The operation completed successfully, and the promise has a resulting value.
  • Rejected: The operation failed, and the promise has a reason for the failure.


3. Creating a Promise:

  • Use the `Promise` constructor to create a new Promise. It takes a function with two parameters: `resolve` and `reject`.
  •  `resolve` is a function to call when the asynchronous operation succeeds, and `reject` is called when it fails.


 const myPromise = new Promise((resolve, reject) => {
 
      // Asynchronous operation
 
      if (/* operation successful */) {
 
        resolve("Operation succeeded!");
 
      } else {
 
        reject("Operation failed!");
 
      }
 
    });


4. Chaining Promises:

  • Promises can be chained together using the `.then()` method, which is called when the promise is resolved.
  • Chaining allows for a more readable and sequential flow of asynchronous operations.

 myPromise
 
      .then(result => {
 
        console.log(result); // Output: Operation succeeded!
 
        return someOtherAsyncOperation();
 
      })
 
      .then(secondResult => {
 
        console.log(secondResult);
 
      })
 
      .catch(error => {
 
        console.error(error); // Handle errors in the chain
 
      });

5. Handling Errors:

  • The `.catch()` method is used to handle errors in the promise chain.
  • If any promise in the chain is rejected, the control jumps to the nearest `.catch()` block.


6. Promise.all() and Promise.race():

  • `Promise.all(iterable)` is used when you have multiple promises and want to wait for all of them to be fulfilled.
  • `Promise.race(iterable)` is used when you want to settle as soon as one of the promises in the iterable settles.


const promises = [promise1, promise2, promise3];
 
 
 
    Promise.all(promises)
 
      .then(results => {
 
        console.log(results); // Array of results when all promises are fulfilled
 
      })
 
      .catch(error => {
 
        console.error(error); // Handle errors in any of the promises
 
      });
 
 


7. Async/Await:

The `async` and `await` keywords provide a syntactic sugar on top of promises, making asynchronous code look more like synchronous code.


 async function fetchData() {
 
      try {
 
        const result = await myPromise;
 
        console.log(result);
 
      } catch (error) {
 
        console.error(error);
 
      }
 
    }
 
 
 
    fetchData();


The `await` keyword is used inside an `async` function to pause execution until the promise is resolved or rejected.

Promises are a fundamental part of modern JavaScript and are widely used for managing asynchronous code in a more structured and maintainable way. They help avoid callback hell and make it easier to reason about the flow of asynchronous operations.

Post a Comment

Previous Post Next Post