简体   繁体   English

承诺-连锁解决/拒绝

[英]Promises - chaining resolves/rejects

I have a function which returns a deferred.promise - jQuery's variant of deferred s however - but the same concept. 我有一个返回deferred.promise的函数-jQuery的deferred s的变体-但概念相同。

Whether the file read is successful or not, I would like to progress to the next part of the chain. 无论文件读取成功与否,我都想继续进行下一步。 Something like the following: 类似于以下内容:

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();
        }
    );

However this, to me, seems like unnecessary code duplication. 但是,对我来说,这似乎是不必要的代码重复。 Because I don't want to break the chain if one of the read fails - so handle each error locally. 因为如果其中一个读取失败,我不想中断链-因此请在本地处理每个错误。

Is there a way around this to make it cleaner and avoid the code duplication? 有没有办法使它更整洁并避免代码重复? I am not too bothered about having the granularity on each readFile call. 对于每个readFile调用的粒度,我不太担心。

I just don't like how I have to repeat code calls in the resolved/rejected callbacks. 我只是不喜欢如何在已解决/已拒绝的回调中重复代码调用。

since you are using the jQuery Promises you could use the function deferred.always . 由于您正在使用jQuery Promises,因此可以使用deferred.always函数。 It get called in case of a success or failure. 成功或失败时都会调用它。 It is like an the finally in an try-catch -Block 它就像一个在finallytry-catch -块

You can easily use it like: 您可以像这样轻松使用它:

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

So in your case you could do something like 因此,在您的情况下,您可以执行以下操作

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

Here you find the documentation: https://api.jquery.com/deferred.always/ 您可以在此处找到文档: https : //api.jquery.com/deferred.always/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM