Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Handling Multiple Asynchronous Requests | Asynchronous JavaScript and APIs
Advanced JavaScript Mastery
course content

Зміст курсу

Advanced JavaScript Mastery

Advanced JavaScript Mastery

1. Classes
2. DOM Manipulation
3. Events and Event Handling
4. Asynchronous JavaScript and APIs

bookHandling 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.

html

index

css

index

js

index

copy

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.

html

index

css

index

js

index

copy

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.

html

index

css

index

js

index

copy

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.

1. What does `Promise.all()` do when provided with an array of promises?
2. Which method would you use to ensure the quickest promise resolves first, regardless of the others?
What does `Promise.all()` do when provided with an array of promises?

What does Promise.all() do when provided with an array of promises?

Виберіть правильну відповідь

Which method would you use to ensure the quickest promise resolves first, regardless of the others?

Which method would you use to ensure the quickest promise resolves first, regardless of the others?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 10
some-alt