[Vuejs]-Why Array.map() with async / await returns strange results?

3👍

Because Array.map doesn’t actually await it’s passed callback. It doesn’t care that you marked it’s callback as async.

Just Array.map your Promises then pass them to Promise.all and let that await everything (in-parallel) for you.

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👍

Try something like this:

.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) => {...}) returns an array of Promises.

This solution would also be faster than what the OP was trying to achieve anyway since it awaits in-parallel.

And notice that you should to avoid awaiting a .then(…) chain.

👤gleam

Leave a comment