开发者

jQuery - turn a function with ajax call, syncronous

开发者 https://www.devze.com 2023-02-20 08:24 出处:网络
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 sy

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


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.


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


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
})
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号