0

well, i know the title isn't the best, but i'll be as clear as possible:

I have a function that does some stuff, and then makes an ajax call with a callback; I don't want to make that ajax call syncronous. what i need is something like:

function theFunctionToCall(){
  //do stuff
  $.post('ajax.php',data, function(){
    //mycallback; 
  })
}

execute(theFunctionToCall, function(){
   //code to execute after the callback from theFunctionToCall is complete
})

is this even possible? how?

Thank You

André Alçada Padez
  • 10,987
  • 24
  • 67
  • 120
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – mhatch Jun 30 '16 at 14:54

3 Answers3

1

You can use jQuery's .queue() to make function calls run in a specified order.

$(document).queue('AJAX', function(next){
    $.post('ajax.php',data, function(){
        // Callback...
        next(); // Runs the next function in the queue
    });
});

$(document).queue('AJAX', function(next){
    // This will run after the POST and its callback is done
    next();  // Runs the next function, or does nothing if the queue is empty
});

$(document).dequeue('AJAX');  // Runs the 1st function in the queue
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

Just have your functions accept an argument to pass the callback function along:

function theFunctionToCall(data, fn) {
    $.post('ajax.php', data, fn);
}

although I don't see what the particular advantage is to trying to have additional functions delegate which ajax methods are passed which callbacks.

mway
  • 4,334
  • 3
  • 26
  • 37
1
function execute(first, callbackFn) {
    first.call(null, callbackFn);
}

function theFunctionToCall(callbackFn){
    //do stuff
    $.post('ajax.php',data, callbackFn)
}

execute(theFunctionToCall, function(){
    //code to execute after the callback from theFunctionToCall is complete
})
wildcard
  • 7,353
  • 3
  • 27
  • 25