javascript - 使用 Array.reduce() 从获取 promise 中提取 JSON 数据

标签 javascript arrays fetch async.js

我正在编写一个 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/

相关文章:

javascript - 递归函数一直返回false

未找到 Javascript 文件

reactjs - React 尝试使用 .map 将来自多个 API 的数据填充到同一个映射容器中

javascript - 上传文件到nodeJS服务器

javascript - 加载页面和覆盖

javascript - 设置 Javascript 中用于排序的 unicode 字符的值

ruby-on-rails - 这似乎只是用最大的数字填充一个数组,为什么?

arrays - Swift - 为什么我不能将一个 Double 数组 append 到另​​一个 Double 数组

java - 如何压缩整数序列?

excel - VBA for Excel : Server Data Not Updating