jquery在$ .deferred()完成后如何做某事?

时间:2013-12-14 00:31:20

标签: jquery jquery-deferred

我很确定我所要求的是简单而明显的,但是我很累,看不到它:(

我的简化示例如下:

function doSomething(){
   doFirst();
   doSecond();
}

function doFirst(){
   $.when(
      //doing an ajax call and getting a result
   )
   .then(
      function(result){
         // doing something with the result
         $(document).append('<div id="first">I am first</div>');
      }
   );
}

function doSecond(){
   $('#first').css({'color':'#900'});
}

doSomething();

但我的文字并没有像预期的那样变红。我相信这是因为函数已经在执行,但是deferred还没有写入DOM。

2 个答案:

答案 0 :(得分:1)

function doSomething() {
    //pass a callback to doFirst which will get executed once the ajax request is completed
    doFirst(function () {
        doSecond();
    });
}

function doFirst(callback) {
    $.when(
    //doing an ajax call and getting a result
    ).then(function (result) {
        // doing something with the result
        $(document).append('<div class="first">I am first</div>');
        callback();
    });
}

function doSecond() {
    $('#first').css({
        'color': '#900'
    });
}

doSomething();

答案 1 :(得分:1)

您可以通过从doFirst()返回承诺来链接承诺:

function doFirst(){
  /* return the `$.when` promise*/
  return $.when(
      //doing an ajax call and getting a result
   )
   .then(function(result){
         // doing something with the result
         $(document).append('<div class="first">I am first</div>');
      }
   );
}

function doSomething(){
   doFirst().then(function(){
         doSecond();
   });  
}

DEMO

由于$.when返回一个承诺,因此只返回没有$.ajax的ajax也会得到相同的结果

function doFirst() {
    /* return the ajax promise*/
    return $.post('/echo/html/', {
        html: '<div id="first">I am first</div>'
    }).then(function (result) {        
        $('body').html(result);
    });
}

DEMO 2