【发布时间】:2019-11-07 04:30:05
【问题描述】:
下面的代码从 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() 可用于收集所有 Promise 并从那里开始工作 - 但它们的数量是未知的。换句话说,我可以使用
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() 的内容是未知的。
【问题讨论】:
标签: javascript promise es6-promise fetch-api