首页 > 解决方案 > 在 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)
})

我想知道有没有更好的解决方案来解决这个问题?

标签: javascriptasynchronousfetch

解决方案


您想为此使用 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
})

推荐阅读