exception handling, thrown errors, within promises

后端 未结 3 1296
梦谈多话
梦谈多话 2021-02-07 04:47

I am running external code as a 3rd party extension to a node.js service. The API methods return promises. A resolved promise means the action was carried out successfully, a f

3条回答
  •  无人及你
    2021-02-07 05:15

    It is almost the most important feature of promises. If it wasn't there, you might as well use callbacks:

    var fs = require("fs");
    
    fs.readFile("myfile.json", function(err, contents) {
        if( err ) {
            console.error("Cannot read file");
        }
        else {
            try {
                var result = JSON.parse(contents);
                console.log(result);
            }
            catch(e) {
                console.error("Invalid json");
            }
        }
    
    });
    

    (Before you say that JSON.parse is the only thing that throws in js, did you know that even coercing a variable to a number e.g. +a can throw a TypeError?

    However, the above code can be expressed much more clearly with promises because there is just one exception channel instead of 2:

    var Promise = require("bluebird");
    var readFile = Promise.promisify(require("fs").readFile);
    
    readFile("myfile.json").then(JSON.parse).then(function(result){
        console.log(result);
    }).catch(SyntaxError, function(e){
        console.error("Invalid json");
    }).catch(function(e){
        console.error("Cannot read file");
    });
    

    Note that catch is sugar for .then(null, fn). If you understand how the exception flow works you will see it is kinda of an anti-pattern to generally use .then(fnSuccess, fnFail).

    The point is not at all to do .then(success, fail) over , function(fail, success) (I.E. it is not an alternative way to attach your callbacks) but make written code look almost the same as it would look when writing synchronous code:

    try {
        var result = JSON.parse(readFileSync("myjson.json"));
        console.log(result);
    }
    catch(SyntaxError e) {
        console.error("Invalid json");
    }
    catch(Error e) {
        console.error("Cannot read file");
    }
    

    (The sync code will actually be uglier in reality because javascript doesn't have typed catches)

提交回复
热议问题