1

The following code works fine without the exception, and if the there is exception in function bar, the program just finished without any output. I have checked Q's source code, it catches the exception and reject it. Spent some time but still don't know what's the proper way to get the exception info.

function foo(val) {
    var deferred = Q.defer();
    if (val) {
        deferred.resolve(val);
    } else {
        deferred.reject(val);
    }

    return deferred.promise;
}

function bar() {
    var deferred = Q.defer();
    foo(true)
    .then(function(res) {
        throw new Error('true error!');
        deferred.resolve(true);
    }, function(err) {
        throw new Error('false error!');
        deferred.reject(false);
    });

    return deferred.promise;
}

bar()
.then(function(res) {
    console.log('true');
}, function(err) {
    console.log('false');
})
.done();
yyhuang
  • 13
  • 3
  • Check [this question](http://stackoverflow.com/questions/20041737/learning-promises-and-exceptions-vs-rejecting-in-q), which is similar to yours. – Paul Mougel Nov 19 '13 at 10:36
  • Thank you. My intention is not to throw exception but to detect exceptions that thrown by other api. – yyhuang Nov 19 '13 at 11:07

1 Answers1

0

First, the deferred whose promise you are returning from bar() is never resolved or rejected (all you do is create it in the first line, do nothing with it, and return it's promise in the last line)

Let's assume you fixed it this way: http://jsfiddle.net/KW9d9/

function bar() {
  var promise = foo(true);

Now (at the end of your code) you are still looking for the errors not on the promise that they are fired in. When calling .than on our first promise, a new promise is returned. Think of 'then' is creating a new promise wrapping a previous one. Fixing it like so will give us the exception thrown in our 'then' promise since Exceptions thrown in the then handlers are used as a reject value. Look at: http://jsfiddle.net/ybefw/

function bar() {  
  return foo(true).then(function(res) {....
Asaf
  • 770
  • 6
  • 15