Home > Web Front-end > JS Tutorial > How to Fetch and Parse Text Data from an Array of URLs with Promise.all?

How to Fetch and Parse Text Data from an Array of URLs with Promise.all?

Susan Sarandon
Release: 2024-10-26 16:16:30
Original
857 people have browsed it

How to Fetch and Parse Text Data from an Array of URLs with Promise.all?

Fetching an Array of URLs with Promise.all

To retrieve an array of text data from a set of URLs, utilizing Promise.all is a suitable approach. Here's how to effectively accomplish this task:

Suppose you have an array of URL strings:

<code class="js">var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"</code>
Copy after login

The desired output is an array of text content:

<code class="js">var text = ['one', 'two', 'three'];</code>
Copy after login

Using Promise.all allows you to chain multiple asynchronous operations. In this case, it can be used to first fetch each URL and subsequently extract the text from each response:

<code class="js">Promise.all(urls.map(url => fetch(url)))
  .then(responses =>
    Promise.all(responses.map(res => res.text()))
  )
  .then(texts => {
    // ...
  });</code>
Copy after login

In the above code, Promise.all is used twice: once to initiate the fetching of all URLs, and a second time to obtain the text content from each response.

An alternative approach, combining both operations into a single Promise.all chain, can be achieved as follows:

<code class="js">Promise.all(urls.map(url =>
  fetch(url)
    .then(resp => resp.text())
))
.then(texts => {
  // ...
});</code>
Copy after login

Additionally, you can further simplify this code using async/await:

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

Both of these approaches effectively utilize Promise.all to achieve the desired result of fetching an array of URLs and extracting the associated text content.

The above is the detailed content of How to Fetch and Parse Text Data from an Array of 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