Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tell javascript to run jquery ajax first

In short, how do I let alert(1) run first:

    $.post('example.php', function() {
        alert(1);
    })
    alert(2);
    alert(3);
    alert(4);

But jquery ajax call seem like run in asynchronous method. So JavaScript will run everything below first, alert(2) to alert(4), then back to the post method, alert(1).

Certainly I can just put the code in the ajax function, but this make no sense when I have dozens of functions, then I would have to add the code to all functions.

    $.post('example.php', function() {
        alert(1);
        example();
    })

    function example() {
        alert(2);
        alert(3);
        alert(4);
    }

I want to get some json data from an ajax call, and use it later. So is there any smart solution?


2021-08-25

after 8 years, introduction of async / await is awesome, i don't really use jquery anymore, so i didn't test the code

await Promise.resolve($.post('example.php', function() {
    alert(1);
    example();
}));

alert(2);
alert(3);
alert(4);
like image 798
aptx Avatar asked Jan 23 '26 06:01

aptx


1 Answers

in jQuery I simply prefer to use $.when and $.then it's easy to do and code is more readable using this.

function CatchTheFish(){
console.log('we are catching the fish');
}
function EattheFish(){
console.log('now time to eat this fish');
}
$.when ( CatchTheFish() ).then( EattheFish() );

This code is work in latest version of jQuery 1.9.1

like image 187
Anirudha Gupta Avatar answered Jan 24 '26 20:01

Anirudha Gupta