"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-14
Browse:801

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:

var urls = ['1.txt', '2.txt', '3.txt']; // Text files containing "one", "two", "three"

The desired output is an array of text content:

var text = ['one', 'two', 'three'];

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:

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

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:

Promise.all(urls.map(url =>
  fetch(url)
    .then(resp => resp.text())
))
.then(texts => {
  // ...
});

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

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3