繁体   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