Titeufggg
Titeufggg

Reputation: 21

Wait for ajax request inside a function : $.Deferred ? $.When ? jQuery

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.

Upvotes: 1

Views: 952

Answers (1)

charlietfl
charlietfl

Reputation: 171669

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

Upvotes: 3

Related Questions