Question

I'm having a problem with callback functions in javascript. What I want to do is: loop on a for and call a function passing i as parameter. With that in mind, I have to loop to the next interaction only after the previous one has been finished. I don't know if this is a problem but inside the function I'm sending i as parameter, I have another callback function. Here is my code:

for(i=0; i<10; i++) {
    aux(i, function(success) {
        /* 
         *  this should be made interaction by interaction
         *  but what happens is: while I'm still running my first interaction  
         *  (i=0), the code loops for i=1, i=2, etc. before the response of 
         *  the previous interaction
         */
        if(!success)
            doSomething();
        else
            doSomethingElse();
    });
}

function aux(i, success) {
    ... //here I make my logic with "i" sent as parameter
    getReturnFromAjax(function(response) {
        if(response)
            return success(true);
        else
            return success(false);
    });
});

function getReturnFromAjax(callback) {
    ...
    $.ajax({ 
        url: myUrl,
        type: "POST",
        success: function (response) {
        return callback(response);
    }
});
}
Was it helpful?

Solution

jQuery's Deferred can be a bit tricky to get right. What you'll have to do is stack your promises in a chain. For example:

var
  // create a deferred object
  dfd = $.Deferred(),

  // get the promise
  promise = dfd.promise(),

  // the loop variable
  i
;

for(i = 0; i < 10; i += 1) {
  // use `then` and use the new promise for next itteration
  promise = promise.then(
    // prepare the function to be called, but don't execute it!
    // (see docs for .bind)
    aux.bind(null, i, function(success) {
      success ? doSomethingElse() : doSomething();
    })
  );
}

// resolve the deferred object
dfd.resolve();

for this to work, aux must also return a promise, but $.ajax already does this, so just pass it through and everything should work:

in aux:

function aux(i, callback) {
  console.log('executing for `aux` with', i);

  // return the ajax-promise
  return getReturnFromAjax(function(response) {
    callback(Boolean(response));
  });
}

in getReturnFromAjax:

function getReturnFromAjax(callback) {
  // return the ajax-promise
  return $.ajax({
    url: '%your-url%',
    type: '%method%',
    success: function (response) {
      callback(response);
    }
  });
}

demo: http://jsbin.com/pilebofi/2/

OTHER TIPS

I'd suggest that you'd look into jQuery's Deferred Objects and jQuery.Deferred()-method instead of making your own callback queue functions (as you are already using jQuery anyway).

Description: A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

I don't have experience with jQuery, but your callback looks a bit fishy to me.

In plain JS I'd suggest trying something among the lines of this:

function yourMainFunction
{   

    function callbackHandler(result) 
    {
        // Code that depends on on the result of the callback
    }

    getAjaxResults(callbackHandler);

}



function getAjaxResults(callbackHandler)
{   

// Create xmlHttpRequest Handler, etc.
// Make your AJAX request

xmlHttp.onreadystatechange = function() 
{
    if (xmlHttp.readyState == 4 && xmlHttp.status==200)
    {
        // Do stuff you want to do if the request was successful
        // Define a variable with the value(s) you want to return to the main function

        callbackHandler(yourReturnVariable);
    }
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top