Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 一旦完成嵌套的获取,如何执行操作?_Javascript_Promise_Es6 Promise_Fetch Api - Fatal编程技术网

Javascript 一旦完成嵌套的获取,如何执行操作?

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

下面的代码从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.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