2014-03-12 45 views
0

我想在jQuery中做一個$ .when()。then($ when()。then(...))的鏈。我不習慣於第一次使用它們的功能。當多個鏈()然後() - 被拒絕的對象

我改變了我的代碼有點我的代碼來表示這種情況:

function setenum(e) 
{ 
    return $.ajax({ 
     url: SetPathUrl1(), 
     type: 'GET', 
     data: { isNew: e.isNew() }, 
     contentType: 'application/json; charset=utf-8', 
     success: function (data, status, xhr) { 
      /*My stuff*/ 
     }, 
     error: function (xhr, status, error) { 
      /*My stuff*/ 
     } 
    }); 
} 

function setdropdown1(e) 
{ 
    return $.ajax({ 
      url: SetPathUrl2(), 
      type: 'GET', 
      data: { isNew: e.isNew() }, 
      contentType: 'application/json; charset=utf-8', 
      success: function (data, status, xhr) { 
       /*Fill my first ddl based on enum*/ 
      }, 
      error: function (xhr, status, error) { 
       /*My stuff*/ 
      } 
     }); 
} 

function setdropdown2(e) 
{ 
    return $.ajax({ 
      url: SetPathUrl3(), 
      type: 'GET', 
      contentType: 'application/json; charset=utf-8', 
      success: function (data, status, xhr) { 
       /*Fill my second ddl based on enum*/ 
      }, 
      error: function (xhr, status, error) { 
       /*My stuff*/ 
      } 
     }); 
} 

function DoOtherStuff(e) 
{ 
    /**/ 
} 

function MainNotWorking(ImportantModel) 
{ 
    $.when(setenum(ImportantModel)) 
    .then(
     $.when(setdropdown1(ImportantModel),setdropdown2(ImportantModel)) 
     .then(
      function() { 
       DoOtherStuff(e); 
      } 
     ) 
     ); 
} 

function MainWorking(ImportantModel) 
{ 

    $.when(setenum(ImportantModel),setdropdown1(ImportantModel),setdropdown2(ImportantModel)) 
    .then(
     function() { 
      DoOtherStuff(e); 
     } 
    ); 

} 

MainNotWorking:訂單完全不尊重,設置setdropdown1setdropdown2是在setenum前,有時也被稱爲。

主打: 當我只有一級的時候,那麼函數DoOtherStuff在所有其他函數之前被調用,但它只有一個級別。我想在setdropdown1setdropdown2之前,然後最後DoOtherStuff之前做多個鏈setenum

+0

「'DoOtherStuff'從來都不是在所有其他函數完成之前調用「,這不是使用Deferreds的要點,在其他函數完成之前不要調用它,或者你真的認爲它是」從不「調用的。 – adeneo

+0

刪除了'永不':P – billybob

+0

試試這個樣子 - > ** http://jsfiddle.net/qT6JZ/1/** – adeneo

回答

1

使用$.when().done(callback)

function MainNotWorking(ImportantModel) { 
    $.when(
     setenum(ImportantModel) 
    ).done(function() { 
     $.when(
      setdropdown1(ImportantModel), 
      setdropdown2(ImportantModel) 
     ).done(DoOtherStuff); 
    }); 
} 
1

首先,你應該傳遞一個函數引用then

.then(function() { ... }) 

你所傳遞的,而不是在第一功能完成後立即執行。

這本身就足夠了,但如果你想「壓扁」了鏈接,你可以做這樣的事情:

$.when(
    setenum(ImportantModel) 
).then(function() { 
    return $.when(
     setdropdown1(ImportantModel), 
     setdropdown2(ImportantModel) 
    ) 
}).then(function() { 
    DoOtherStuff(); 
}); 

這裏有一個演示:http://jsfiddle.net/44e5Y/