Home  >  Article  >  Web Front-end  >  How can I use `Promise.all` to retrieve data from an array of URLs and create a corresponding array of text content?

How can I use `Promise.all` to retrieve data from an array of URLs and create a corresponding array of text content?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-29 02:38:02342browse

How can I use `Promise.all` to retrieve data from an array of URLs and create a corresponding array of text content?

Utilizing Promise.all for Retrieving an Array of URLs

Retrieving data from multiple sources can be a common task when dealing with web requests. Promise.all is a useful tool in JavaScript that allows for the execution of multiple async operations concurrently and combining their results into a single Promise.

The Problem:
Imagine you have an array of URLs and aim to create an object that mirrors the structure of the URL array but with the content of each URL's text file.

var urls = ['1.txt', '2.txt', '3.txt']; // These files contain "one", "two", "three" respectively.
var result = ['one', 'two', 'three']; 

Approaching with Promise.all:
When attempting to solve this problem using Promise.all initially, you may encounter difficulties. Let's examine a flawed approach:

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

Here, Promise.all is applied to an array of Promises representing fetch requests. However, this approach fails to produce the desired array of ['one', 'two', 'three'] as intended. To rectify this, consider these refined solutions:

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

This code initiates fetch requests for all URLs, followed by processing the responses to retrieve the text content of each URL. The result is an array of text values that can be further processed. Alternatively, the code can be simplified using modern JavaScript features:

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

Here, async/await syntax is utilized to handle asynchronous operations more concisely.

Employing Promise.all judiciously in conjunction with these techniques, you can effectively fetch and process data from an array of URLs, paving the way for subsequent data manipulation tasks.

The above is the detailed content of How can I use `Promise.all` to retrieve data from an array of URLs and create a corresponding array of text content?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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