javascript - 在 foreach 循环中获取多个链接

标签 javascript asynchronous fetch-api

我有如下链接数组:

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/

相关文章:

javascript - 如何将提示的值添加到一起?

javascript - 重新加载/播放 swiffer 容器

Javascript 'this' 和异步 post 方法

javascript - 使用数组参数获取 API GET 请求。如何?

javascript - JS - 使用 Fetch API 获取文本或 JSON

javascript - javascript 中的 mac 地址验证 (00 :00:00:00:00:00)

javascript - JMeter - WebDriver 采样器 - waitForPopUp

java - 使用@Async调用方法与在新线程中调用方法

validation - Node.js 中的 POST 主体和一些异步条件检查

javascript - Javascript如何使用Fetch API跨域加载文本或JSON数据?