javascript - 在 foreach 循环中获取多个链接
问题描述
我有这样的链接数组:
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
})
推荐阅读
- android - 在链式工作继续中仅观察一个 WorkRequest
- ejabberd - 未提供主机服务 (ejabberd)
- amazon-web-services - 从 root 帐户运行 athena 查询时访问被拒绝错误
- vb.net - 设置 ComboBox 的 SelectedIndex 时出现 ArgumentOutOfRangeException
- c++ - 有没有在 C++ 中创建自定义比较器的统一方法?
- javascript - 基于值的角度开关不透明度
- python - 防止多个python脚本同时访问单个文件
- html - 从一个导航到另一个时如何刷新其他组件(Angular 7,router.navigate)中的数据?
- oracle - 删除Oracle表空间/数据文件并重启数据库
- powerquery - 如何在 Power Query 中编写递归查询以遍历树