简体   繁体   中英

Unhandled rejection in Bluebird

I have the following code. It works fine when f2 throws no error.

If there is an error, it generates an Unhandled rejection Error .

What's the proper way to rewrite the code to avoid Unhandled rejection Error and propagate it correctly to catch in f1 ?

let Bluebird = require('bluebird'),
    mkdirp = Bluebird.promisify(require('mkdirp')),
    request = Bluebird.promisify(require('request')),
    writeFile = Bluebird.promisify(require('fs').writeFile);

function f1() {
    .........
    f2(path, fileName, options).then(.....).catch(....); 
}

function f2(path, fileName, options) {
    p = mkdirp(path).then(request(options).then(res => {
        if (res[0].statusCode === 200) {
            writeFile(fileName, res[0].body);
            return res[0].body;
        } else {
            throw new Error(res[0].statusCode + ': ' + res[0].body);
        }
    }));
    return p;
}

The problem is that you are passing a promise into .then() in f2 . .then() will ignore anything that is not a function, so all that f2 is really returning is a promise for mkdirp(this.path) and that's a big bug for a few reasons. If an error is thrown in request(options) 's then handler, then there will be nothing to handle it.

Also, you are not doing anything to handle a possible error from writeFile . If you call writeFile , you either need to return a promise chain that includes it, or add logic to handle it within f2 .

Since it looks like you can run mkdirp() and request() in parallel here, but you are not using the result of mkdirp() I would say this is the way to go:

function f2(path, fileName, options) {
    var p = mkdirp(path).return(request(options)).then(res => {
        if (res[0].statusCode === 200) {
            return writeFile(fileName, res[0].body)
            .return(res[0].body);
        } else {
            throw new Error(res[0].statusCode + ': ' + res[0].body);
        }
    });
    return p;
}

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