Home >Web Front-end >JS Tutorial >How to Efficiently Fetch Data from Multiple URLs with Promise.all?
Conquering Multiple URL Fetches with Promise.all
In the realm of asynchronous programming, Promises offer a powerful mechanism to handle asynchronous tasks like fetching data from multiple URLs. As you've encountered, trying to fit this use case into the Promise.all paradigm can be a stumbling block.
Let's dissect your attempted solution:
var promises = urls.map(url => fetch(url)); var texts = []; Promise.all(promises) .then(results => { results.forEach(result => result.text()).then(t => texts.push(t)) })
This method suffers from a crucial flaw: forEach returns neither an array nor a Promise, leaving you in a promise-void with no way to access the fetched texts.
To rectify this, Promise.all must be employed twice, once to fetch the URLs and once to extract the text from the responses:
Promise.all(urls.map(u=>fetch(u))).then(responses => Promise.all(responses.map(res => res.text())) ).then(texts => { … })
Alternatively, you can streamline the process by combining the fetch and text retrieval into one step:
Promise.all(urls.map(url => fetch(url).then(resp => resp.text()) )).then(texts => { … })
For a more concise solution, embrace the power of async/await:
const texts = await Promise.all(urls.map(async url => { const resp = await fetch(url); return resp.text(); }));
These approaches grant you the ability to handle multiple URL fetches efficiently, enabling you to build the desired object containing the extracted texts.
The above is the detailed content of How to Efficiently Fetch Data from Multiple URLs with Promise.all?. For more information, please follow other related articles on the PHP Chinese website!