0

Say I have a function as follows:

var randomFn = function(){
   var response = '';
   async.whilst(
      // Test
      function(){
         return i < 5;
      },
      // Iteratee
      function(callback){
         // Random code that sets response to '5' after some attempts;
      },
      // Callback
      function(err, n){
         // Runs if error is encountered or iteratee stopped
      }

   );

   return response;
}

The async module while allow the iteratee function to run repeatedly, until the first test function no longer returns true. My question is, can I be guaranteed the return for my randomFn() will only be executed once the everything inside the async function has completed?

So what exactly is the order of execution, or the rule for execution...?

rugrln
  • 128
  • 1
  • 6
  • 4
    That's not how that works. Your `randomFn` will always return an empty string. Always. – Jared Smith Oct 24 '17 at 14:43
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Oct 24 '17 at 14:44
  • The AJAX question above sheds some light on this question, but then the question is how can I return the response variable, because the return keyword inside the callback function of the async function links to the callback function, not to the main function... – rugrln Oct 24 '17 at 15:37
  • 1
    Per the answers to that question, **you can't**. It is perfectly reasonable to *want* to do this, but for various good reasons that are too long to explain here the language won't let you. You have basically two options: use nested callbacks or Promises, both approaches are mentioned in the answers to that question. – Jared Smith Oct 24 '17 at 15:40

0 Answers0