Reputation: 34627
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
});
Upvotes: 1
Views: 94
Reputation: 11052
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);
};
Upvotes: 1