How to Fetch Multiple Data from Multiple Endpoints with Promise.all in JavaScript

preview_player
Показать описание
---

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

When trying to fetch multiple datasets from different URLs using fetch, many developers run into the challenge of dealing with promises effectively. Take the following example:

[[See Video to Reveal this Text or Code Snippet]]

What's Going Wrong?

In this code snippet, you might notice that the .json() method is called on the responses, but it does not return a usable format for the next .then. Instead, it returns a promise that needs to be resolved. This can lead to confusion, as the code may log an unresolved promise rather than the actual data you want.

The Solution: Resolving Promises Efficiently

To properly resolve and handle the data returned from the APIs, we need to make a small adjustment to the way we chain our promises. Here's the step-by-step breakdown of the solution:

Step 1: Modify Your First .then

[[See Video to Reveal this Text or Code Snippet]]

Step 2: Understanding The Change

Logging the Data: With the proposed adjustment, you are now able to log the actual data for both airports and flights instead of pending promises.

Benefits of This Approach

Cleaner Code: Reduces the complexity of handling multiple asynchronous requests.

Better Error Handling: A single .catch means you can manage errors gracefully from any of the fetch requests.

Enhanced Readability: This approach is easier to understand and maintain.

Conclusion

Рекомендации по теме