在foreach循环中获取多个链接

时间:2018-11-19 15:25:23

标签: javascript asynchronous fetch

我有很多这样的链接:

let array = ['https://1','https://2','https://3']

比起我想循环所有元素并对其进行读取。仍然是异步提取的,因此我得到了更多请求,这样就解决了从数组中删除元素的问题:

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)
})

我想知道有更好的解决方案吗?

2 个答案:

答案 0 :(得分: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
})

答案 1 :(得分:0)

在这种情况下,我将使用Promise.all()。首先从每个响应中获取身体。然后在完成各自的承诺后对响应进行一些处理:

let urls = ['https://1','https://2','https://3']

Promise.all(urls.map(url =>
   // do something with this response like parsing to JSON
   fetch(url,{mode: 'no-cors'}).then(response => response)
)).then(data => {
   // do something with the responses data
})