Traditionally, making multiple network requests in JavaScript would require you to chain them sequentially. This can be inefficient, as each request blocks until the previous one completes. This is particularly noticeable with the I/O bound nature of HTTP requests.
// Inefficient approach
fetch('url1')
.then(response => response.json())
.then(data1 => {
// Process data1
fetch('url2')
.then(response => response.json())
.then(data2 => {
// Process data2
console.log('Data 1 and 2 processed');
});
});
Promises provide a cleaner and more efficient way to handle asynchronous operations, including network requests. They allow you to chain requests without blocking, and handle errors gracefully.
// Efficient approach using Promise.all
Promise.all([
fetch('url1').then(response => response.json()),
fetch('url2').then(response => response.json())
])
.then(([data1, data2]) => {
// Process both data1 and data2
console.log('Data 1 and 2 processed');
})
.catch(error => {
console.error('Error:', error);
});
Here's a breakdown of the code:
Promise.all([promise1, promise2, ...])
: Takes an array of promises and returns a new promise that resolves when all of the promises in the array have resolved.Promise.all
.