在函数内等待ajax请求:$ .Deferred? $。什么时候? jQuery的

时间:2016-12-11 19:30:20

标签: jquery ajax deferred resolve .when

如何在延迟函数内完成ajax?示例:

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

问题是他的功能必须等到调用并完成ajax内部并继续其他脚本。

谢谢。

1 个答案:

答案 0 :(得分:3)

您可以链接承诺then()

$.ajax已经返回一个

时,也无需创建新的承诺

所以在action()内,您可以执行以下操作:

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

    var myAjaxCall = ajaxCall();

     return myAjaxCall.then(function(result){
        // do stuff here after ajax is successfull  
     });
}