Jolly Boy
Jolly Boy

Reputation: 15

call fetch requests synchronously using promises

I would like to call fetch for each item in an array, but I would like to do them one at a time, only starting a new one when the previous one has finished. Is there a way to solve this using promises only? I solved it using recursion, but I think my solution is a bit silly. My solution is as follows:

//call fetch once for each word in the array
let promises = "words to fetch from this array".split(' ')
fetchCall(promises.shift())

function fetchCall(word) {

  return new Promise(function(resolve, reject) {
    console.log('this is simulating a fetch call')
    setTimeout(function() {
      return resolve('resolved')
    }, 1000)

  }).then(function() {
    //only make the next fetch call when the previous one has finished
    if (promises.length > 0) {
      fetchCall(promises.shift())
    }
  })
}

Upvotes: 0

Views: 148

Answers (1)

Kateryna S
Kateryna S

Reputation: 69

my lovely async for each

async function asyncForEach(array, promiseFn) {
  for (let index = 0; index < array.length; index++) {
    await promiseFn(array[index], index, array)
  }
}

//call fetch once for each word in the array
let promises = "words to fetch from this array".split(' ')

Then call asyncForEach for your array

await asyncForEach(promises, item => {
  // add async to simulate delay from xhr request
  return new Promise( async function(resolve, reject){
    console.log('this is simulating a fetch call')
    await setTimeout(function(){
      return resolve('resolved')
    }, 1000)
    
  }).then(function(){
    // print item after promise resolve
    console.log(item);
  })
})

OR You can use Promise.all

//call fetch once for each word in the array
let promises = "words to fetch from this array".split(' ')


let promisesArr = promises.map(e => new Promise((resolve, reject) => {
  setTimeout(function(){
    console.log('this is simulating a fetch call', e)
    resolve(e)
  }, 1000)
}))

// res is array or resolve arguments 
Promise.all(promisesArr).then(res => console.log(res))

Upvotes: 1

Related Questions