2015-11-12 27 views
0

我有一個函數返回一個deferred.promise - 但是jQuery的deferred s變體 - 但是同樣的概念。承諾 - 鏈接解析/拒絕

無論文件讀取是否成功,我想進入下一部分鏈。像下面這樣:

var a, 
    b, 
    c; 

readFile(fileNameA) 
    .then(
     function (res) { 
      a = res; // res might be null 

      return readFile(fileNameB); 
     }, 
     function (err) { 
      return readFile(fileNameB); 
     } 
    ) 
    .then(
     function (res) { 
      b = res; // res might be null 

      return readFile(fileNameC); 
     }, 
     function (err) { 
      return readFile(fileNameC); 
     } 
    ) 
    .then(
     function (res) { 
      c = res; // res might be null 

      callPostLogic(); 
     }, 
     function (err) { 
      callPostLogic(); 
     } 
    ); 

但是,對我來說,這似乎是不必要的代碼重複。因爲如果其中一個讀取失敗,我不想中斷鏈 - 所以在本地處理每個錯誤。

有沒有辦法解決這個問題,使它更清潔,避免代碼重複?我不太在意每個readFile調用的粒度。

我只是不喜歡我必須在解決/拒絕的回調中重複代碼調用。

回答

3

因爲您使用的是jQuery Promise,所以您可以使用函數deferred.always。它會在成功或失敗的情況下被調用。這就像在try-catch - 塊

您可以輕鬆地使用它像一個的finally

$.get("test.php").always(function() { 
    alert("$.get completed with success or error callback arguments"); 
}); 

所以你的情況,你可以做類似

readFile(fileNameA) 
    .always(function() { 
     return readFile(fileNameB); 
    }) 
    .always(function() { 
     return readFile(fileNamec); 
    }) 
    .always(function() { 
     // finished 
    }); 

這裏您可以找到的文檔:https://api.jquery.com/deferred.always/

+0

它的工作原理 - 謝謝:) – keldar