简体   繁体   中英

Node.js Bluebird - promise error being returned as null

I have a series of promises where if any of them throw an error it bubbles up to the top promise - kind of like global error catching.

Here's a simplified version of how I've got things setup:

function bar() {
    return new Promise(function(resolve,reject) {
        var err = new Error('This is an error');
        err.name = 'Permission';
        return reject(null,err);
    });
}

function foo() {
    return new Promise(function(resolve,reject) {
        bar()
            .then(function(results) {
                return resolve(results);
            })
            .then(null,function(error) {
                console.log('Error caught'); //This shows
                console.log(error); //outputs null
                return reject(error);
            });
    });
}

foo()
    .then(function(results) {
        console.log(results);
    })
    .then(null,function(error) {
        //this never gets reached
    });

For some reason although the error function runs the value of 'error' is null. Any ideas on what would cause this?

Thanks!

The reject function takes only one argument, the reason. So, when you call:

reject(null, err);

You are passing null as the rejection reason and the err argument is not used. Change your code to this:

reject(err);

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