javascript 使用promise同步调用获取请求

mzsu5hc0  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(144)

我想对数组中的每一个元素调用fetch,但是我想一次只调用一个,只有当前一个元素完成后才开始一个新的元素。***有没有一种方法可以只用promise来解决这个问题?***我用递归解决了这个问题,但是我觉得我的解决方案有点傻。我的解决方案如下:

//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())
    }
  })
}
cbwuti44

cbwuti441#

我可爱的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(' ')

然后为阵列调用asyncForEach

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);
  })
})

或者你可以使用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))

相关问题