为什么Array.map()与异步/等待返回奇怪的结果?

问题描述 投票:0回答:2

这是预期它返回的一切我的代码工作版本:

***.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}]

这里发生了什么事?

javascript vue.js async-await arrow-functions
2个回答
3
投票

由于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)
  })

2
投票

尝试是这样的:

.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

© www.soinside.com 2019 - 2024. All rights reserved.