【发布时间】:2020-04-14 13:16:50
【问题描述】:
我正在编写一个then() 语句,用于从fetch() 的响应数组中提取json 数据。在下面的代码中,queries 是一系列对fetch() 的调用返回的承诺数组。我正在使用 async/await 作为响应,否则将返回承诺而不解决(我在 this question 中找到了解决方案)。
我的第一次尝试工作正常,当我推入jsonified 时,我获得了一个以承诺作为元素的数组:
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() 重构代码?
【问题讨论】:
标签: javascript arrays fetch async.js