我有关于循环和如何重写整个数组以获取所需数据的问题。我需要获取数据,然后在next fetch中嵌套"id“,以获取数据并合并2个数组。如何在另一个fetch中获取循环外的数据,然后合并数据?
`fetch(URL)
.then(res => res.json())
.then(data => {
let companies = data;
for (let i = 0; i <= companies.length; i++) {
fetch(`URL${companies[i].id}`)
.then(res => res.json())
.then(data => {
there loop is sending me data needed from 2nd fetch and 300 another data from first fetch.
});
// console.log(companies[i].name);
}
})
.catch(error => console.log(error));`发布于 2020-03-09 23:34:21
您可以使用await进行第二次抓取。在第一个fetch中声明一个数组,只要在第二个fetch中检索到数据,就推入数组。然后你就可以在for循环之外访问了。
fetch('https://api.github.com/users?since=135')
.then(res => res.json())
.then(async (data) => {
let users = data;
let arr = [];
for (let i = 0; i <= users.length; i++) {
const response = await fetch(`https://api.github.com/users/${companies[i].login}`);
const user = response.json();
arr.push(user);
}
console.log(arr);
})
.catch(error => console.log(error));发布于 2020-03-09 23:44:02
您可以使用Promise.all()等待所有fetch请求完成。Promise.all接受一个promise数组,并返回一个promise,该promise在所有传递的promise解析时解析。如果其中一个通过的承诺被拒绝,Promise.all也会拒绝。
fetch(URL)
.then(res => res.json())
.then(data => {
let companies = data;
let promises = [];
for (let i = 0; i <= companies.length; i++) {
let promise = fetch(`URL${companies[i].id}`)
.then(res => res.json());
promises.push(promise);
}
Promise
.all(promises)
.then(dataArrays => {
// dataArrays[0] is the result from company 0
// dataArrays[1] is the result from company 1 and so on
})
.catch(error => console.log(error));
// console.log(companies[i].name);
}
})
.catch(error => console.log(error));但是,如果可能,将所有companies请求合并为一个,并在后端合并它们的数据将是最佳解决方案,因为这样会更高效。
https://stackoverflow.com/questions/60603491
复制相似问题