Making multiple fetch api calls how to check if all calls have finished?

11,962

Assuming you have an array of urls named urls

// separate function to make code more clear
const grabContent = url => fetch(url)
     .then(res => res.text())
     .then(html => (/* process html here */))

Promise
    .all(urls.map(grabContent))
    .then(() => console.log(`Urls ${urls} were grabbed`))
Share:
11,962
Muhammad Umer
Author by

Muhammad Umer

I know how much I know

Updated on June 05, 2022

Comments

  • Muhammad Umer
    Muhammad Umer almost 2 years

    I am grabbing content from multiple urls. Fetch api uses promises all over.

    So my code for one requests looks like this

    fetch(url).then((response)=>response.text()).then(function(html) { //stuff });

    now i have array of urls and multiple calls will be made how do i know if all calls have finished.

    i tried using Promise.all but if you see there are two promises for every request. Is there a better way, also Promise.all support is not that good either.

  • clurect
    clurect almost 8 years
    You can also just do Promise.all([url1,url2]).then() as well
  • jfriend00
    jfriend00 almost 8 years
    @clurect - That isn't enough. Promise.all() accepts an array of promises. It won't do anything useful if you just pass it an array of URLs.
  • Yury Tarabanko
    Yury Tarabanko almost 8 years
    @clurect urls is an array of strings (From OP: now i have array of urls ). Wrapping it with a Promise doesn't make much sense.
  • clurect
    clurect almost 8 years
    ah yes, my bad. It should've been promises.