Handling multiple promises
Mahek Afzal
React Native Developer | IOS | Android | Creating Seamless Mobile Experience | Mobile App Developer
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?
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?
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?
领英推荐
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?
// 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
Using these techniques helps manage multiple asynchronous actions efficiently and handle various scenarios with promises effectively.