1

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!

richwol
  • 1,065
  • 2
  • 11
  • 24
  • You probably want `reject(err)` in your `bar` function for not getting `null` – Bergi Jul 22 '15 at 19:44
  • 1
    Your `foo` function uses the [promise constructor antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Jul 22 '15 at 19:45
  • Uhoh! Time to do some more research I think! – richwol Jul 22 '15 at 19:47
  • 1
    Yeah, just do `function foo() { return bar().catch(function(err) { console.log("Error caught and rethrown", err); throw err; }) }` – Bergi Jul 22 '15 at 19:51

1 Answers1

1

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);
jfriend00
  • 683,504
  • 96
  • 985
  • 979