Home >Web Front-end >JS Tutorial >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>
The desired output is an array of text content:
<code class="js">var text = ['one', 'two', 'three'];</code>
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>
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>
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>
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!