我有如下链接数组:
let array = ['https://1','https://2','https://3']
我想循环所有元素并对它们运行 fetch。仍然 fetch 是异步的,所以我收到请求的次数更多,我处理这个问题,从数组中删除元素,如下所示:
array.forEach((link,index) => {
fetch(link, {mode: 'no-cors'}).then(function () {
//more stuff not inportant
}).catch(e => {
console.error('error', e);
});
array.splice(index,1)
})
我想知道是否有更好的解决方案来解决这个问题?
最佳答案
您想为此使用 Promise.all,如下所示:
// store urls to fetch in an array
const urls = [
'https://dog.ceo/api/breeds/list',
'https://dog.ceo/api/breeds/image/random'
];
// use map() to perform a fetch and handle the response for each url
Promise.all(urls.map(url =>
fetch(url)
.then(checkStatus)
.then(parseJSON)
.catch(logError)
))
.then(data => {
// do something with the data
})
关于javascript - 在 foreach 循环中获取多个链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53377774/