使用promises同步调用fetch请求



我想为数组中的每个项目调用fetch,但我想一次只做一个,只在前一个完成时开始一个新的。是否有一种方法来解决这个使用承诺?我用递归解决了这个问题,但我认为我的解决方案有点傻。我的解决方案如下:

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

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(' ')

然后调用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))

相关内容

  • 没有找到相关文章

最新更新