簡體   English   中英

承諾-連鎖解決/拒絕

[英]Promises - chaining resolves/rejects

我有一個返回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調用的粒度,我不太擔心。

我只是不喜歡如何在已解決/已拒絕的回調中重復代碼調用。

由於您正在使用jQuery Promises,因此可以使用deferred.always函數。 成功或失敗時都會調用它。 它就像一個在finallytry-catch -塊

您可以像這樣輕松使用它:

$.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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM