[英]Why Array.map() with async / await returns strange results?
这是我的代码的有效版本,该版本按预期返回所有内容:
***.then(r => r.json()).then(async r => {
for (let i = 0; i < r.length; i++) {
let pipeline = r[i];
pipeline.collapsed = true;
pipeline.levels = await this.getPipelineLevels(pipeline.id);
}
this.project.pipelines.items = r;
})
这是返回错误结果的“中断”版本:
****.then(r => r.json()).then(r => {
let pipelines = r.map(async (value) => {
let levels = await this.getPipelineLevels(value.id);
return {...value, collapsed: true, levels: levels};
});
this.project.pipelines.levels = pipelines;
*.map()
之后在console.log(JSON.stringify(pipelines))
在控制台中出现奇怪的输出:
[{"_c":[],"_s":0,"_d":false,"_h":0,"_n":false},{"_c":[],"_s":0,"_d":false,"_h":0,"_n":false}]
这里发生了什么事?
因为Array.map
实际上并不await
所以它已传递了回调。 不在乎您将其回调标记为async
。
只需Array.map
您的Promises,然后将它们传递给Promise.all
,让它等待一切(并行)为您服务。
const getPipelineLevels = id => new Promise(resolve => { setTimeout(() => resolve({ id: id, foo: 'bar' }), 500) }) const idx = [1,2,3,4,5] const tasks = idx.map(id => { return getPipelineLevels(id) .then(value => ({ ...value, bar: 'baz' })) }) Promise.all(tasks) .then(results => { console.log(results) })
尝试这样的事情:
.then(async r => {
let pipelines = await Promise.all(r.map(async (value) => {
let levels = await this.getPipelineLevels(value.id);
return {...value, collapsed: true, levels: levels};
}));
this.project.pipelines.levels = pipelines;
});
Array.map(async (value) => {...})
返回一个Promises数组。
由于并行等待,因此该解决方案也将比OP试图实现的解决方案更快。
请注意,您应该避免等待.then(...)链 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.