Javascript 一旦完成嵌套的获取,如何执行操作?
下面的代码从API获取一个数组,然后针对该数组的每个元素检索进一步的数据Javascript 一旦完成嵌套的获取,如何执行操作?,javascript,promise,es6-promise,fetch-api,Javascript,Promise,Es6 Promise,Fetch Api,下面的代码从API获取一个数组,然后针对该数组的每个元素检索进一步的数据 fetch('https://reqres.in/api/users') 。然后(r=>r.json())。然后(r=>{ r、 data.forEach(x=>{ 取('https://reqres.in/api/users') 。然后(r=>r.json())。然后(r=>{ r、 data.forEach(x=>console.log(x.id)) }) }) }) …但脚本启动时,无法知道传递给Promise.a
fetch('https://reqres.in/api/users')
。然后(r=>r.json())。然后(r=>{
r、 data.forEach(x=>{
取('https://reqres.in/api/users')
。然后(r=>r.json())。然后(r=>{
r、 data.forEach(x=>console.log(x.id))
})
})
})
…但脚本启动时,无法知道传递给Promise.all()的内容
没关系,您可以使用map
而不是forEach
,然后等待结果:
fetch('https://reqres.in/api/users')
.then(r => r.json()).then(r =>
Promise.all(r.data.map(x =>
fetch('https://reqres.in/api/users') // (presumably there's some parameter here, you're not just repeating the same call...)
.then(r => r.json())
.then(r => {
r.data.forEach(x => console.log(x.id))
})
))
);
除非在
map
中创建的所有承诺都已解决,或其中任何承诺已被拒绝,否则上述退货链将无法结算。您可以使用array.map
创建承诺数组:
const allPromises = r.data.map(x => {
return fetch('https://reqres.in/api/users/' + x)
.then(r => r.json())
});
Promise.all(allPromises).then(data => console.log('All data is loaded', data))
也许这是解决问题的办法,但你的方法似乎有问题
fetch('https://reqres.in/api/users')
.then(r => r.json()).then(r => {
return Promise.all(r.data.map(x => {
return fetch('https://reqres.in/api/users')
.then(r => r.json()).then(r => {
r.data.forEach(x => console.log(x.id))
})
)
})
})
换句话说,您可以使用嵌套的Promise.all,并在执行then
s的内部代码时返回它。还有一个重要的注意事项,对于迭代异步调用,应该使用map
而不是forEach