Handling multiple promises

Handling multiple promises

Handling multiple promises at once is a common scenario in JavaScript, especially when dealing with asynchronous operations that can run in parallel. JavaScript provides several methods to handle multiple promises at once. Here are some questions and answers about handling promises together:

1. How do you wait for multiple promises to resolve?

Answer: You can use Promise.all to wait for multiple promises to resolve. Promise.all takes an array of promises and returns a new promise that resolves when all the promises in the array have resolved. If any promise rejects, Promise.all immediately rejects with that reason.

const promise1 = fetchDataFromAPI1();
const promise2 = fetchDataFromAPI2();
const promise3 = fetchDataFromAPI3();

Promise.all([promise1, promise2, promise3])
  .then(([result1, result2, result3]) => {
    console.log("All promises resolved:", result1, result2, result3);
  })
  .catch((error) => {
    console.error("One of the promises rejected:", error);
  });
        

2. What if you want to handle promises independently and see results as they come in?

  • Answer: Promise.allSettled is useful here. It waits for all promises to settle (either resolve or reject) and returns an array of objects describing each promise’s outcome. This method doesn’t reject if one of the promises fails.

const promise1 = fetchDataFromAPI1();
const promise2 = fetchDataFromAPI2();
const promise3 = fetchDataFromAPI3();

Promise.allSettled([promise1, promise2, promise3])
  .then((results) => {
    results.forEach((result, index) => {
      if (result.status === "fulfilled") {
        console.log(`Promise ${index + 1} resolved with`, result.value);
      } else {
        console.error(`Promise ${index + 1} rejected with`, result.reason);
      }
    });
  });
        

3. How do you get the first resolved promise out of a group of promises?

  • Answer: You can use Promise.race, which returns a promise that resolves or rejects as soon as any of the promises in the array resolves or rejects. This is useful when you want to proceed as soon as the fastest promise completes.

const promise1 = fetchDataFromAPI1(); // might take 3 seconds
const promise2 = fetchDataFromAPI2(); // might take 1 second

Promise.race([promise1, promise2])
  .then((result) => {
    console.log("First resolved promise:", result);
  })
  .catch((error) => {
    console.error("First rejected promise:", error);
  });
        

4. How can you retry a promise if it fails?

  • Answer: You can create a function that attempts to call a promise again if it fails. Here’s an example of a retry function that retries a promise a specified number of times.

function retryPromise(fn, retries = 3) {
  return fn().catch((error) => {
    if (retries > 1) {
      return retryPromise(fn, retries - 1);
    }
    throw error;
  });
}

// Usage
retryPromise(() => fetchDataFromAPI(), 3)
  .then((result) => {
    console.log("Data fetched successfully:", result);
  })
  .catch((error) => {
    console.error("Failed after 3 retries:", error);
  });
        

5. How do you handle multiple asynchronous actions where each action depends on the previous one?

  • Answer: You can chain promises sequentially using .then or use async/await to handle promises one after the other

// Using Promise chaining
fetchDataFromAPI1()
  .then((result1) => fetchDataFromAPI2(result1))
  .then((result2) => fetchDataFromAPI3(result2))
  .then((finalResult) => {
    console.log("Final result:", finalResult);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

// Using async/await
async function fetchSequentially() {
  try {
    const result1 = await fetchDataFromAPI1();
    const result2 = await fetchDataFromAPI2(result1);
    const finalResult = await fetchDataFromAPI3(result2);
    console.log("Final result:", finalResult);
  } catch (error) {
    console.error("Error:", error);
  }
}
        

6. How do you cancel a promise?

Answer: Native JavaScript promises don’t support direct cancellation. However, you can use AbortController to cancel fetch requests, which is particularly useful in React Native when dealing with network requests. Here’s an example of how to cancel a fetch request:

const controller = new AbortController();
const { signal } = controller;

fetch("https://jsonplaceholder.typicode.com/todos/1", { signal })
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => {
    if (error.name === "AbortError") {
      console.log("Fetch aborted");
    } else {
      console.error("Fetch error:", error);
    }
  });

// Cancel the request
controller.abort();
        

Summary

  • Promise.all: Waits for all promises to resolve or for any to reject.
  • Promise.allSettled: Waits for all promises to settle (either resolve or reject), useful for getting all results regardless of failures.
  • Promise.race: Resolves or rejects as soon as the first promise completes.
  • retryPromise: A custom function to retry promises in case of failure.
  • async/await: A cleaner syntax for handling asynchronous tasks sequentially.
  • AbortController: Useful for canceling fetch requests.

Using these techniques helps manage multiple asynchronous actions efficiently and handle various scenarios with promises effectively.



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

Mahek Afzal的更多文章

社区洞察

其他会员也浏览了