如何等待直到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被调用并完成后再继续其他脚本。

谢谢。

最佳答案

您可以链接承诺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
     });
}

关于jquery - 在函数内等待ajax请求:$ .Deferred? $。什么时候? jQuery的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41090222/

10-11 15:46