Search code examples
javascriptarraysasynchronouses6-promise

Filling an array with results of an async function


I need to set up an array of objects, however its attributes need to come from an async function.

For me to do this, I run .map() on the array, and do whatever it is I need to do on each element, but I need the result of the async function for them.

The way I am doing it right now I get PromiseStatus and PromiseValue as my result, which isn't what I want. I basically just want my PromiseValue in my array.

Here is my current code:

function processMyArray (array) {
  const processedArray = array.map(x => {
    return myAsyncFunction(x)
      .then((result) => {
        const { attribute1, attribute2 } = result
        return {
          attribute1,
          attribute2
        }
      })
  })
  return processedArray
}

// the rough code for myAsyncFunction()
 myAsyncFunction (data) {
    return Promise.all(
      [
        this.getAttribute1(data),
        this.getAttribute2(data)
      ]
    )
    .then(([attribute1, attribute2]) => {
      return {
        attribute1, attribute2
      }
    })
  }

Solution

  • Either wrap the mapped into

    Promise.all(array.map(...))
    

    or use cool ES 7 stuff ( await in for loops ):

    async function processMyArray (array) {
      const result = [];
      for(const x of array){ //x is a bad name by the way
        const { attribute1, attribute2 } = await myAsyncFunction(x);
        result.push({ attribute1, attribute2 });
      }
      return result;
    }