4

I think this is a fairly simple question, but I primarily program in ruby and ma having trouble wrapping my head around asynchronous functions in javascript. Specifically, I have a method that is supposed to populate an array with results fetched asynchronously from an API. I am able to get the results fine, but I can't seem to return the array after it has been populated. Rather, the return statement executes before the promise is resolved, so an empty array is returned. Simplified code example below:

async function getAnimalSounds(animals){
   var sounds = []
   for (const a of animals){
     asynchronously_fetch_sound(a).then((result) => {
       sounds.push(result)
     })
   }
   
   return sounds // sounds returns as an empty array
}

Thank you in advance!

Matt
  • 478
  • 4
  • 14
  • 1
    See the "multiple asynchronous operations" part of [my answer here](https://stackoverflow.com/a/43766002/157247). – T.J. Crowder Nov 29 '20 at 15:12

3 Answers3

7

The problem here is that you are using a plain for loop to traverse the animals array. Loops in NodeJS won't wait for the promise of the current iteration to resolve before moving onto the next, so the loop will finish before you have resolved your promises.

The best thing to do is to construct an array of promises you want to resolve, and then call Promise.all on that array.

async function getAnimalSounds(animals){
    const promises = animals.map(a => asynchronously_fetch_sound(a))
    const sounds = await Promise.all(promises)

    return sounds
}

Or if you're happy to use the Bluebird library (docs here), you can do this:

const Bluebird = require('bluebird') // import Bluebird library

async function getAnimalSounds(animals){
    const sounds = await Bluebird.map(animals, (a) => asynchronously_fetch_sound(a))

    return sounds
}

Remember that since you have written an async function, you will need to wait for it to resolve before doing anything with its output; either by awaiting it or by calling .then(...).

tgall
  • 132
  • 4
  • 1
    In both examples you can use `const sounds = Promise.all()` or `const sounds. = Bluebird.map()`, you don't need to `await` the result, as returning it will wrap it back into a Promise anyway since your functions are `async`. – Nick Parsons Nov 12 '21 at 11:55
0

You should add await for the asynchronous method call.

async function getAnimalSounds(animals){
   var sounds = []
   for (const a of animals){
     const result = await asynchronously_fetch_sound(a);
     sounds.push(result)
   }
   
   return sounds // sounds returns as an empty array
}

However, the best practice is to use Promise.all()

async function getAnimalSounds(animals){
   var sounds = []
   const promises = []
   for (const a of animals){
     promises.push(asynchronously_fetch_sound(a));
   }
   sounds = await Promise.all(promises);

   return sounds;
}
wangdev87
  • 8,611
  • 3
  • 8
  • 31
0

You can use Promise.all() to achieve that:

function getAnimalSounds(animals){
   return Promise.all(animals.map(a => asynchronously_fetch_sound(a)));
}
falinsky
  • 7,229
  • 3
  • 32
  • 56