在 foreach 循环中获取多个链接
Fetch multiple links inside foreach loop
我有一系列这样的链接:
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)
})
不知道有没有更好的办法解决这个问题?
你想为此使用 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
})
回复将按完成的顺序出现。
const urls = [1,2,3,4];
// using async await with for loop
const der = async (x) => {
const f = await fetch(`https://jsonplaceholder.typicode.com/todos/${x}`)
const j = await f.json()
return j;
};
urls.forEach(async(url) => {console.log(await der(url))});
// using promise all with then method
Promise.all(urls.map(x =>
fetch(`https://jsonplaceholder.typicode.com/todos/${x}`).then(response => response.json())
)).then(data => {
console.log(data)
})
我有一系列这样的链接:
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)
})
不知道有没有更好的办法解决这个问题?
你想为此使用 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
})
回复将按完成的顺序出现。
const urls = [1,2,3,4];
// using async await with for loop
const der = async (x) => {
const f = await fetch(`https://jsonplaceholder.typicode.com/todos/${x}`)
const j = await f.json()
return j;
};
urls.forEach(async(url) => {console.log(await der(url))});
// using promise all with then method
Promise.all(urls.map(x =>
fetch(`https://jsonplaceholder.typicode.com/todos/${x}`).then(response => response.json())
)).then(data => {
console.log(data)
})