嵌套的fetch完成后如何执行操作?

3
以下代码从API获取一个数组,然后对该数组的每个元素都检索更多的数据。

fetch('https://reqres.in/api/users')
  .then(r => r.json()).then(r => {
    r.data.forEach(x => {
      fetch('https://reqres.in/api/users')
        .then(r => r.json()).then(r => {
          r.data.forEach(x => console.log(x.id))
        })
    })
  })

一旦数据完全检索,我需要对其执行某些操作。如何做到这一点?

问题在于,这是一组异步解析的Promise。可以使用Promise.all()来收集所有的Promises并从那里开始工作-但是它们的数量事先是未知的。换句话说,我可以使用

a = fetch('https://reqres.in/api/users')
b = fetch('https://reqres.in/api/users')
Promise.all([a, b]).then(x => console.log('all resolved here'))

但是传递给 Promise.all() 的内容在脚本开始时是未知的。

3个回答

2

...但是当脚本开始运行时,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 中所有的 Promise 被解决或者任何一个被拒绝,才会结束。请注意保留 HTML 标签。

2

你可以使用Array.map创建一组Promise数组:

最初的回答:

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))

1
也许这是解决方案,但你的方法似乎有些问题。
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的结果返回。重要提示:在进行迭代异步调用时,应使用map而不是forEach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接