Martin Larocque
Martin Larocque

Reputation: 190

call function after multiple loops of fetch()

If i want to call doStuff() when multiple loops of fetch are finnish, how would i approach it ?

im assuming i need to call a function every time a fetch is done and check if concat of both array length is at the last one ?

let array1 = [1,2]
let array2 = [7,8]

array1.map(function(item){
  fetch("/api/execution/"+item, {
      method: "POST",
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      }
  })
});

array2.map(function(item){
  fetch("/api/something/"+item, {
      method: "POST",
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      }
  })
});

//call doStuff only when all the fetchs are done

function doStuff(){
  console.log("yay")
}

Upvotes: 1

Views: 57

Answers (1)

Pointy
Pointy

Reputation: 413720

You're using .map() to launch the requests but you're not saving the returned Promise instances.

let p1 = array1.map(function(item){
  return fetch("/api/execution/"+item, {
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  })
});

And similarly for array2. You can then concatenate the two arrays of Promises and use Promise.all():

let p1 = array1.map(function(item){
  return fetch("/api/execution/"+item, {
    method: "POST",
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  })
});

let p2 = array2.map(function(item){
  return fetch("/api/something/"+item, {
      method: "POST",
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
      }
  })
});

Promise.all(p1.concat(p2)).then(function(fetchedValues) {
  // all fetch calls are finished
});

Upvotes: 4

Related Questions