以下代码从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()
的内容在脚本开始时是未知的。