javascript - 如何通过异步等待使用 map 数据

标签 javascript node.js

我想要 .map 而不是 for 循环,但我仍然困惑如何使用它,这里是我的数据

const arr =  [
  {
    name: "John",
    subject : [
      {
        subject_id : 1,
        score :20
      }
    ]
  },
  {
    name: "Doe",
     subject : [
      {
        subject_id : 2,
        score :20
      }
    ]
  }
]

我想将主题详细信息添加到主题数组中

async getData() {
  for (let i in arr) {
    let data = arr[i];
    for (let i in data.subject) {
        const subject = data.subject[i];
        //this line code will get subject detail
        const getSubject = await this.getSubject(subject);
        subject["subjectData"] = getSubject;
    }
  }
}

一切正常,但是我如何使用map而不是for循环

输出示例

{
  name: "Doe",
   subject : [
    {
      subject_id : 2,
      score :20,
      subjectData: {
        //some detail
      }
    }
  ]
}

这就是我想做的

const newData = arr.map(async data => {
    const getSubject = data.subject;
    const subject = getSubject.map(async zp02 => {
      const getSubject = await this.getSubject(subject);
        return { getSubject };
    });
    return { ...data, subject };
});

我的主题总是返回 null 。

我想使用map的原因是因为我读到很多人说它比for循环更快

  • 他们是否无论如何都使用 map 而不是 for
  • 我正在学习干净的代码,你能给我一个如何在嵌套 for 循环中重构代码的想法

最佳答案

检查一下 https://dev.to/jhalvorson/how-do-i-use-async-await-with-array-map-1h3f .

摘自这篇文章:

您不能 async/await Array.map,因为同步代码不会等待异步代码解析,而是会触发函数并继续。这是我们所期望的行为,因为我们不希望 Array.map 阻塞线程,否则当 Array.map 执行其操作时什么都不会运行。知道这一点很酷,但是,如果我们需要等待 Array.map(),它并没有真正帮助我们。

幸好有一个解决方案,我们可以利用 Promise.all 来实现我们想要的

//For example, the following won't work:
const postIds = ['123', 'dn28e29', 'dn22je3'];

const posts = await postIds.map(id => {
return axios
 .get(`https://example.com/post/${id}`)
 .then(res => res.data)
 .catch(e => console.error(e));
}

console.log(posts) // [] it returns the promise, not the results 💩

//But this will:
const postIds = ['123', 'dn28e29', 'dn22je3'];

const posts = posts.map(post => {
  return axios
    .get(`https://example.com/post/${post.id}`)
    .then(res => res.data)
    .catch(e => console.error(e));
}

Promise.all(posts).then(res => console.log(`We have posts: ${res}!`));

我们不是立即返回 Array.map,而是将其分配给一个变量并将该变量传递给 Promise.all,一旦解析完成,我们就可以访问 Array.map 返回的新数组。

关于javascript - 如何通过异步等待使用 map 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60374272/

相关文章:

javascript - 异步加载 vue.config.js 用于预渲染元数据

javascript - 调用父对象函数

node.js - 默认情况下,Sequelize.js 是否会转义 SQL 注入(inject)的输入?

node.js - 无法在 TypeScript 中设置断点 - VS Code

Javascript:在 <br> 之前和之后向内容添加元素

javascript - 迭代地将数组中的第一个和最后一个数字相加

javascript - AngularJS 和 UI 路由器 : Why do $state. go() 和 $location.path() 在交互式控制台中不起作用?

javascript - 快速路由分离

node.js - AWS 上的 IISNode 上托管的 MongoDB 应用程序的高 TTFB

javascript - 在 Node js 服务器上托管多个游戏