Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning array populated in loop by async function

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!

like image 872
Matt Avatar asked Oct 14 '25 17:10

Matt


1 Answers

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(...).

like image 75
tgall Avatar answered Oct 17 '25 07:10

tgall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!