Home > Web Front-end > JS Tutorial > How to Efficiently Fetch Data from Multiple URLs with Promise.all?

How to Efficiently Fetch Data from Multiple URLs with Promise.all?

Patricia Arquette
Release: 2024-10-29 05:24:02
Original
289 people have browsed it

How to Efficiently Fetch Data from Multiple URLs with Promise.all?

Conquering Multiple URL Fetches with Promise.all

In the realm of asynchronous programming, Promises offer a powerful mechanism to handle asynchronous tasks like fetching data from multiple URLs. As you've encountered, trying to fit this use case into the Promise.all paradigm can be a stumbling block.

Let's dissect your attempted solution:

var promises = urls.map(url => fetch(url));
var texts = [];
Promise.all(promises)
  .then(results => {
     results.forEach(result => result.text()).then(t => texts.push(t))
  })
Copy after login

This method suffers from a crucial flaw: forEach returns neither an array nor a Promise, leaving you in a promise-void with no way to access the fetched texts.

To rectify this, Promise.all must be employed twice, once to fetch the URLs and once to extract the text from the responses:

Promise.all(urls.map(u=>fetch(u))).then(responses =>
    Promise.all(responses.map(res => res.text()))
).then(texts => {
    …
})
Copy after login

Alternatively, you can streamline the process by combining the fetch and text retrieval into one step:

Promise.all(urls.map(url =>
    fetch(url).then(resp => resp.text())
)).then(texts => {
    …
})
Copy after login

For a more concise solution, embrace the power of async/await:

const texts = await Promise.all(urls.map(async url => {
  const resp = await fetch(url);
  return resp.text();
}));
Copy after login

These approaches grant you the ability to handle multiple URL fetches efficiently, enabling you to build the desired object containing the extracted texts.

The above is the detailed content of How to Efficiently Fetch Data from Multiple URLs with Promise.all?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template