0

这是我的代码的工作版本,它按预期返回所有内容:

***.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))after *.map()

[{"_c":[],"_s":0,"_d":false,"_h":0,"_n":false},{"_c":[],"_s":0,"_d":false,"_h":0,"_n":false}]

这里发生了什么事?

4

2 回答 2

3

因为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)
  })

于 2019-02-05T17:08:13.497 回答
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) => {...})返回一个 Promise 数组。

该解决方案也将比 OP 试图实现的更快,因为它并行等待。

请注意,您应该避免等待 .then(...) 链

于 2019-02-05T16:54:22.763 回答