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!

1
  • 1
    See the "multiple asynchronous operations" part of my answer here. Commented Nov 29, 2020 at 15:12

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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;
}

1 Comment

Be aware that this will mean all the fetches happen sequentially, not simultaneously
0

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

function getAnimalSounds(animals){
   return Promise.all(animals.map(a => asynchronously_fetch_sound(a)));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.