use*_*288 1 javascript asynchronous fetch
我有一系列像这样的链接:
let array = ['https://1','https://2','https://3']
Run Code Online (Sandbox Code Playgroud)
比我想循环所有元素并在它们上运行 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)
})
Run Code Online (Sandbox Code Playgroud)
我想知道有没有更好的解决方案来解决这个问题?
you*_*ter 10
您想为此使用 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
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4072 次 |
| 最近记录: |