简体   繁体   中英

Promises - chaining resolves/rejects

I have a function which returns a deferred.promise - jQuery's variant of deferred s however - but the same concept.

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.

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 . It get called in case of a success or failure. It is like an the finally in an try-catch -Block

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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