Table Of Contents
Problem
You need to make multiple HTTP requests and they're running one after another, taking too long when they could run simultaneously.
Solution
// Sequential requests (slow)
async function sequentialRequests() {
const user = await fetch('https://jsonplaceholder.typicode.com/users/1');
const posts = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const todos = await fetch('https://jsonplaceholder.typicode.com/todos/1');
return {
user: await user.json(),
posts: await posts.json(),
todos: await todos.json()
};
}
// Concurrent requests (fast)
async function concurrentRequests() {
const [userRes, postsRes, todosRes] = await Promise.all([
fetch('https://jsonplaceholder.typicode.com/users/1'),
fetch('https://jsonplaceholder.typicode.com/posts/1'),
fetch('https://jsonplaceholder.typicode.com/todos/1')
]);
return {
user: await userRes.json(),
posts: await postsRes.json(),
todos: await todosRes.json()
};
}
// With error handling
async function concurrentWithErrorHandling() {
const requests = [
fetch('https://jsonplaceholder.typicode.com/users/1'),
fetch('https://jsonplaceholder.typicode.com/posts/1'),
fetch('https://jsonplaceholder.typicode.com/todos/1')
];
const results = await Promise.allSettled(requests);
return results.map(async (result, index) => {
if (result.status === 'fulfilled') {
return await result.value.json();
} else {
console.error(`Request ${index} failed:`, result.reason);
return null;
}
});
}
Explanation
Promise.all()
runs requests simultaneously instead of waiting for each one. Use Promise.allSettled()
when some requests might fail - it waits for all to complete regardless of success or failure.
This approach dramatically reduces total time when making multiple independent API calls, as they execute in parallel rather than sequentially.
Share this article
Add Comment
No comments yet. Be the first to comment!