1

I want to make a loop as follows

asyncFunction(function(returnedVariable){
    if(returnedVariable < 10 )
        // call asyncFunction() again
    else
        // break/exit
});

Is this possible?

I can't call it from inside because then

asyncFunction(function(returnedVariable){
    if(returnedVariable < 10 )
        asyncFunction(function(returnedVariable){
            // ???
        });
    else
        // break/exit
});
3
  • Sounds like the most basic case of recursion. Commented Mar 15, 2014 at 16:32
  • Not exactly recursion, since there should only be one instance of aSyncFunction on the stack, but the same principle. Commented Mar 15, 2014 at 16:33
  • @Tarmo & Jeremy I'm not able to get what's so basic about it. I've edited it to explain the problem exactly... Commented Mar 15, 2014 at 16:37

1 Answer 1

1

EDIT - original answer at bottom. after rereading I think you can just do this for your case (although i've never tried referring to a function inside itself like this):

function asyncFunction(callback){ /* ... do stuff then callback() */ };

function myCallback(returnedVariable){
  if(returnedVariable < 10 ){
    asyncFunction(myCallback);
  } else {
    // break/exit
  }
}

asyncFunction(myCallback);

i'm sure there's a way to do it without a library but for simplicity I always just use caolan/async which works in both node and browser:

var async = require('async');
// for browser, above this script:
// <script src="/path/whatever/async.js" type="text/javascript"></script>

function wrapper(callback){
  var lastReturn = 0;

  function test(){ 
    return lastReturn < 10 
  };

  function iterate(next){
    lastReturn = doSomethingWithPrev(lastReturn);
    next();
  };

  function complete(err){
    if(err){ return callback(err) };
    callback(null, lastReturn);
  };

  async.whilst(test, iterate, complete);
};
Sign up to request clarification or add additional context in comments.

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.