我正在编写一个 then()
语句,用于从 fetch()
的响应数组中提取 json 数据。在下面的代码中,queries
是一系列调用 fetch()
返回的 promise 数组。我正在使用 async/await 作为响应,因为否则 promise 将在没有解决的情况下返回(我在 this question 中找到了解决方案)。
我的第一次尝试工作正常,当我进入 jsonified
时,我获得了一个以 promises 作为元素的数组:
return Promise.all(queries)
.then(async(responses)=> {
let jsonified = [];
for (let res of responses){
jsonified.push(await(res.json()));
}
return jsonified;
}.then(data=> ...
但是当我进行重构并尝试使用 Array.reduce()
时,我意识到当我插入累加器而不是获取以 promise 作为元素的数组时,acc 是 改为指定为 promise 。
.then(responses=> {
return responses.reduce(async(acc, next) => {
acc.push(await(next.json()));
return acc;
}, [])
})
我可以毫无问题地使用第一个版本,程序运行正常,但是 Array.reduce()
内部发生了什么? 为什么将 promise 插入累加器会返回 promise 而不是数组?我如何使用 Array.reduce()
重构代码?
最佳答案
虽然这不是您所要求的,但您可以避免必须使用 reduce
的痛苦,而只需利用您已经拥有的 Promise.all()
使用:
return Promise.all(queries.map(q => q.then(res => res.json()))
.then(data => {...})
这是一种更短的方式,当您回过头来阅读它时也不那么头疼。
关于javascript - 使用 Array.reduce() 从获取 promise 中提取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59452118/