Home > Web Front-end > JS Tutorial > body text

How to Efficiently Retrieve Text from an Array of URLs Using Promise.all?

Susan Sarandon
Release: 2024-10-27 15:10:29
Original
938 people have browsed it

How to Efficiently Retrieve Text from an Array of URLs Using Promise.all?

How to Leverage Promise.all to Retrieve an Array of URLs

Consider this scenario: you have an array of URLs and desire to obtain an object with an array of corresponding text from the files at those URLs. The Promise.all function provides a convenient approach for handling this task.

Initially, the code you attempted used Promise.all to retrieve the promises for each URL. However, the subsequent call to results.forEach may cause confusion. This function triggers a callback for each element, resulting in an array of undefined values.

The correct approach involves using Promise.all twice. The first instance fetches the responses from the URLs, while the second converts the responses to text and returns an array of these texts.

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

Alternatively, you can simplify the code by obtaining the text from the response directly:

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

With async/await syntax, the code becomes even more concise:

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

By employing this approach, you can effectively fetch an array of URLs and obtain an object with the corresponding text values.

The above is the detailed content of How to Efficiently Retrieve Text from an Array of URLs Using 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!