Javascript 在foreach循环中获取多个链接

Javascript 在foreach循环中获取多个链接,javascript,asynchronous,fetch,Javascript,Asynchronous,Fetch,我有一系列这样的链接: let array = ['https://1','https://2','https://3'] 然后我想循环所有元素并对它们运行fetch。仍然获取是异步的,因此我多次获取请求,我处理此问题时从数组中删除元素如下: array.forEach((link,index) => { fetch(link, {mode: 'no-cors'}).then(function () { //more stuff not inportant

我有一系列这样的链接:

let array = ['https://1','https://2','https://3']
然后我想循环所有元素并对它们运行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
})

你想用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
})

在本例中,我将使用
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
})

在本例中,我将使用
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
})

对迭代的数组进行变异不是一种好的做法。为什么这里需要这个?您可能需要调查一下。对迭代的数组进行变异不是一个好的做法。你为什么需要这个?你可能想调查一下。那第一个
然后
是干什么的?@ScottSauyet我想我们可以删除它,但是你可能想解析数据,我会添加一条注释来解释感谢那第一个
然后
是干什么的?@ScottSauyet我想我们可以删除它,但你可能想解析数据,我会添加一条评论来解释谢谢