Friday, 12 July 2024

Javascript Promise

JavaScript Promises: 
  Promise.all(): The Promise.all() method accepts an iterable (such as an array of promises) and returns a single promise. It resolves when all input promises have resolved successfully. If any of the input promises reject, the returned promise will also reject. Example: JavaScript
const promise1 = fetch('https://api.sureshsharma.net/data1');
const promise2 = fetch('https://api.sureshsharma.net/data2');

Promise.all([promise1, promise2])
  .then(([response1, response2]) => {
    // Handle both responses here
  })
  .catch((error) => {
    // Handle errors
  });
Promise.race(): The Promise.race() method takes an iterable of promises and returns a new promise. It resolves or rejects as soon as the first promise in the iterable resolves or rejects. Useful for scenarios like setting a timeout for an operation. Example: JavaScript
const timeoutPromise = new Promise((resolve, reject) => {
  setTimeout(() => reject('Timeout'), 5000);
});

const fetchDataPromise = fetch('https://api.sureshsharma.net/data');

Promise.race([timeoutPromise, fetchDataPromise])
  .then((response) => {
    // Handle the first resolved promise (either timeout or data)
  })
  .catch((error) => {
    // Handle errors (timeout or fetch failure)
  });
Promise.finally(): The finally() method allows you to specify a callback that runs regardless of whether the promise is resolved or rejected. Useful for cleanup tasks (e.g., closing resources, resetting state). Example: JavaScript
fetchDataPromise
  .then((data) => {
    // Process data
  })
  .catch((error) => {
    // Handle errors
  })
  .finally(() => {
    // Cleanup or final actions
  });
Promise.any(): The Promise.any() method returns a promise that resolves with the value of the first fulfilled promise in the iterable. If all promises reject, it rejects with an array of rejection reasons. Useful when you want to proceed with the first successful result. Example: JavaScript
const promises = [promise1, promise2, promise3];

Promise.any(promises)
  .then((result) => {
    // Handle the first successful response
  })
  .catch((errors) => {
    // Handle all rejections
  });
  
Share:

0 Comments:

Post a Comment