gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:06:11 25 4
gpt4 key购买 nike

我想要 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com