这是预期它返回的一切我的代码工作版本:
***.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;
与console.log(JSON.stringify(pipelines))
后*.map()
控制台奇怪的输出:
[{"_c":[],"_s":0,"_d":false,"_h":0,"_n":false},{"_c":[],"_s":0,"_d":false,"_h":0,"_n":false}]
这里发生了什么事?
由于Array.map
实际上并不await
它传递回调。它不在乎你标记它的回调为async
。
只是Array.map
你的承诺,然后通过他们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) => {...})
返回承诺的阵列。
该解决方案也将是比什么OP是想无论如何实现的,因为它在平行等待更快。
同时注意,你应该到avoid awaiting a .then(…) chain。