Зміст курсу
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Handling Multiple Asynchronous Requests
In many real-world applications, you may need to run multiple asynchronous tasks simultaneously or decide which one finishes first. JavaScript provides two key methods to handle such scenarios: Promise.all()
and Promise.race()
.
Promise.all(): Running Tasks in Parallel
Promise.all()
allows you to run multiple promises in parallel. It returns a single promise that resolves when all the promises in the array resolve, or it rejects as soon as one promise rejects. This is useful when you need all asynchronous operations to complete successfully before proceeding.
index
index
index
The fetchMultipleResources
function sends three requests simultaneously to fetch a post, user, and comments data. With Promise.all()
, all three requests are initiated together, and the function waits until all promises resolve. Once resolved, the results are destructured into separate variables (post
, user
, and comments
). The post title, user name, and total number of comments are then displayed in the HTML. This approach is efficient when you need all requests to complete before proceeding, as it reduces overall wait time by running tasks concurrently.
Promise.race(): Handling the First Resolved Promise
Promise.race()
returns a single promise that resolves or rejects as soon as the first promise in the array settles (either resolves or rejects). This is useful when you are interested in the fastest result, such as timing out a request if it takes too long.
index
index
index
The fetchWithTimeout
function creates a timeoutPromise
that rejects after 3 seconds, simulating a timeout. Simultaneously, a fetchPromise
requests data from an API. With Promise.race()
, the function awaits whichever promise settles first. If the fetch completes within 3 seconds, the post title is displayed. Otherwise, if the fetch takes too long, the timeout triggers, and an error message ("Request timed out!") is shown in the HTML. This approach is ideal for handling situations where a quick response is essential.
Use Cases for Running Requests in Parallel vs. Sequentially
When to Use Parallel Requests (Promise.all())
Parallel requests are ideal when fetching data from multiple independent sources, as they allow all requests to run simultaneously. For instance, when loading user data, posts, and comments for a dashboard, each request is separate and does not rely on the others, so they can be fetched in parallel to enhance performance. This approach minimizes the total waiting time, as the requests are processed concurrently rather than one after another.
When to Use Sequential Requests
In some cases, tasks need to be completed in a specific order, meaning one must finish before the next can start. For these dependent requests, you can use async/await
in a loop or chain .then()
calls, avoiding Promise.all()
.
An example would be first fetching user data and then, using the retrieved user ID, fetching the user's posts. In such scenarios, each request relies on the results of the previous one, necessitating a sequential approach.
index
index
index
This example demonstrates making sequential requests where each request depends on the result of the previous one. In fetchUserDataSequentially
, the function first fetches user data from the API. Once the user data is received and parsed, the user's ID is used in a second request to fetch the user's posts. The results are then displayed in the HTML, showing the user's name and the number of posts. This sequential approach is necessary when requests are interdependent, ensuring that each request completes before initiating the next.
Дякуємо за ваш відгук!