0

RESOLVED See answer.

I have a recursive async call that is being resolved at the first call, but I would like to resolve it at the end of the recursivity (where I put 'return "1"'). Any help?

function parent(){
    asyncCall().then(function(result){
       console.log(result);
    });
}


function asyncCall(parameters){
    var promises = [];
    promises.push(
            anotherAsyncFunction(Parameters).then(function (returnedData) {
                if (returnedData==1) {
                    return "1"; //Should resolve here.
                } else {
                    parameters.modify(returnedData);
                    promises.push(asyncCall(parameters)); //Why resolves here??
                }

            })
        );
   return jQuery.when.apply(null, promises);
}

Thanks a lot for your time!

Mario Levrero
  • 3,345
  • 4
  • 26
  • 57

1 Answers1

0

Based on: AngularJS, promise with recursive function

I've resolved it changing from an array of promises to a deferred object passed all the way through. So now is working:

function asyncCall(parameters, deferred){
    if (!deferred) {
        deferred = jQuery.Deferred();
    }

    anotherAsyncFunction(Parameters).then(function (returnedData) {
         if (returnedData==1) {
            return deferred.resolve("1"); 
         } else {
            parameters.modify(returnedData);
            asyncCall(parameters, deferred); //Passing deferred object
        }
    });
    return deferred.promise();
}
Community
  • 1
  • 1
Mario Levrero
  • 3,345
  • 4
  • 26
  • 57