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

    评论

报告相同问题?