Error is not thrown inside a deferred method

76 views Asked by At

Can somebody explain to me why my error is not thrown in my first example? And why it is when I use process.nextTick() ?

var deferred = require('deferred');

// This code does not work. 
// Error seems to never been thrown and script kind of freeze without saying anything.
deferred.resolve().then(function(){
    console.log('deferred resolved');
    throw new Error('Synchronous error thrown in deferred.then()');
});

// This code does work. 
// I just embedded the throw in the process.nextTick() method.
deferred.resolve().then(function(){
    console.log('deferred resolved');
    process.nextTick(function(){
        throw new Error('Synchronous error thrown in deferred.then()');
    });
});

Why do I need to wait the nextTick to throw an error inside the then() ...

Any explanation will be appreciated. Thx

I have seen this post (No errors thrown/displayed when in a deferred callback). But it gives only half an answer ...

1

There are 1 answers

1
Jerome WAGNER On BEST ANSWER

The behavior of deferred seems reasonable to me in your cases.

In the second case, I don't think that deferred has a way to catch the error thrown in the nextTick callback. So the error is thrown.

In the first case, deferred catches it and considers that that resulting promise in in failed state. The deferred documentation states that if you want it to effectively throw an error that pushed the promise into failed state, you have to call done

deferred.resolve().then(function(){
  console.log('deferred resolved');
  throw new Error('Synchronous error thrown in deferred.then()');
}).done();

See https://github.com/medikoo/deferred#ending-chain for documentation