weixin_33726318 2016-07-18 17:31 采纳率: 0%
浏览 32

在AJAX中使用Deferred

I have a series of js functions that are making database calls using ajax, and I need them to finish and update variables before moving to the final function. I'm trying to use jquery $.when and am having no luck...in the attached jsfiddle you can see that the final function result is being displayed before the two primary functions are being updated.

http://jsfiddle.net/b20hvyyp/

var x1 = '%';
var x2 = '%';

main();

function main(){
    logProgress('start');
    $.when(a(), b()).done(logProgress(x1 + x2));
}

// called by main()
function a() {
    return $.ajax("/echo/html").pipe(function(data){
            function changex1 () {
            x1 = 'x1Changed';
        };

        setTimeout(changex1(),2000);
        logProgress(x1);
    });
}

// called by a()
function b() {
        return $.ajax("/echo/html").pipe(function(data){
            function changex2 () {
            x2 = 'x2Changed';
        };

        setTimeout(changex2(),5000);
        logProgress(x2);
    });
}

function logProgress(message){
    $('#progress').append('<li>'+message+'</li>');
}

Any help would be greatly appreciated!!

  • 写回答

2条回答 默认 最新

  • weixin_33701617 2016-07-18 18:19
    关注

    according to Deffered documentation your code should be like this:

    var d1 = $.Deferred();
    var d2 = $.Deferred();
    
    main();
    
    function main(){
        logProgress('start');
        $.when( d1, d2 ).done(function ( x1, x2 ) {
          logProgress(x1 + x2)
        });
        a();
        b();
    }
    
    // called by main()
    function a() {
      return $.ajax("/echo/html").then(function(data){
            x1 = 'x1Changed';
            logProgress(x1);
          d1.resolve(x1);
      });
    }
    
    // called by a()
    function b() {
      return $.ajax("/echo/html").then(function(data){
            x2 = 'x2Changed';
            logProgress(x2);
          d2.resolve(x2);
      });
    }
    
    function logProgress(message){
        $('#progress').append('<li>'+message+'</li>');
    }
    

    when expects Defereds, defereds should be resolved of rejected, i'm not sure why you used timeouts as they really caused delay of execution setting of x1 and x2 to after main function

    评论
  • weixin_33709609 2016-07-18 18:26
    关注

    Two things should be noted here. The functions a() & b() returns deferred objects from the ajax call. These deferred objects will be resolved as soon as the ajax calls complete. So, there is no way for you to detect the execution of timeout callbacks. The next thing is, when() function takes a list of deferred object and returns a single deferred object which will be resolved once all the input deferred objects are resolved. So, the done function on the when() returned deferred should get a callback function instead of a statement like logProgress(x1 + x2). Here is the link with modifications that works: Link

    var x1 = '%';
    var x2 = '%';
    
    main();
    
    function main(){
        logProgress('start');
        console.log('asdf')
        $.when(a(), b()).done(function() {
        logProgress(x1 + x2)
        });
    //  a().done(function(){
    //    logProgress(x1 + x2);
    //  });
    }
    
    // called by main()
    function a() {
        logProgress('a called');
      return $.ajax("/echo/html").pipe(function(data){
        function changex1 () {
            x1 = 'x1Changed';
        };
        
        changex1();
        logProgress(x1);
      });
    }
    
    // called by a()
    function b() {
        logProgress('b called')
      return $.ajax("/echo/html").pipe(function(data){
        function changex2 () {
            x2 = 'x2Changed';
        };
        
        changex2();
        logProgress(x2);
      });
    }
    
    function logProgress(message){
        $('#progress').append('<li>'+message+'</li>');
    }
    <ul id="progress">
    </ul>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 express连接mssql,每条额外附加了语句
  • ¥20 IQOO12如何有效ADB方法
  • ¥15 ios如何获取用户的订阅情况
  • ¥15 复杂表达式求值程序里的函数优先级问题
  • ¥15 求密码学的客成社记ji着用
  • ¥35 POI导入树状结构excle
  • ¥15 初学者c语言题目解答
  • ¥15 div editable中的光标问题
  • ¥15 mysql报错1415Not allowed to return a result set from a trigger 不知如何修改
  • ¥60 Python输出Excel数据整理,算法较为复杂