【问题标题】:Wait for ajax request inside a function : $.Deferred ? $.When ? jQuery等待函数内的 ajax 请求: $.Deferred ? $. 什么时候? jQuery
【发布时间】:2016-12-11 19:30:20
【问题描述】:

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

谢谢。

【问题讨论】:

  • 你永远无法解析action函数中的Deferred

标签: jquery ajax deferred resolve .when


【解决方案1】:

你可以链接 promise then()'s。

$.ajax已经返回一个时,也不需要创建一个新的promise

所以在action() 中,你可以执行以下操作:

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

    var myAjaxCall = ajaxCall();

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

【讨论】:

  • 但是 action() 是在另一个包含 deferred 的函数内部调用的。
  • 不知道这意味着什么......这不是问题中显示的内容
  • 谢谢你的回答
猜你喜欢
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
  • 2018-08-05
相关资源
最近更新 更多