1

How to wait until the ajax is done inside a deferred function ? Example :

    function action() {
        console.log('action is called');

        var deferred = $.Deferred();

        console.log('do some actions...');

        //Wait until the ajax is completed and continue script
        var myAjaxCall = ajaxCall();

        //Execute te next scripts only after the ajax done

        console.log('do some actions...');

        return deferred.promise();
    }


    function ajaxCall() {
        console.log('ajaxCall is called');

        return $.ajax('url').then(function() {
            console.log('success  ajaxCall');
        });
    }

    action().then(function () {
        console.log('after action is done and ajaxCall is done');
    });

The probleme is that he function must wait until the ajax inside is called and done and continue other scripts.

Thank you.

Titeufggg
  • 21
  • 3

1 Answers1

3

You can chain promise then()'s.

Also there is no need to create a new promise when $.ajax already returns one

So inside action() you can do something like:

 function action() {
    console.log('action is called'); 

    var myAjaxCall = ajaxCall();

     return myAjaxCall.then(function(result){
        // do stuff here after ajax is successfull  
     });
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150