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!

4
  • You probably want reject(err) in your bar function for not getting null Commented Jul 22, 2015 at 19:44
  • 1
    Your foo function uses the promise constructor antipattern! Commented Jul 22, 2015 at 19:45
  • Uhoh! Time to do some more research I think! Commented Jul 22, 2015 at 19:47
  • 1
    Yeah, just do function foo() { return bar().catch(function(err) { console.log("Error caught and rethrown", err); throw err; }) } Commented Jul 22, 2015 at 19:51

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Spot on, how did I miss that :|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.