承诺 - 链接 resolves/rejects

Promises - chaining resolves/rejects

我有一个函数 returns 是 deferred.promise - jQuery 是 deferred 的变体 - 但概念相同。

无论文件读取是否成功,我都想进入链的下一部分。类似于以下内容:

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 调用的粒度。

我只是不喜欢在 resolved/rejected 回调中必须重复代码调用的方式。

由于您使用的是 jQuery Promise,因此您可以使用函数 deferred.always。它在成功或失败的情况下被调用。它就像 try-catch-Block

中的 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/