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 ...
The behavior of
deferredseems reasonable to me in your cases.In the second case, I don't think that
deferredhas a way to catch the error thrown in thenextTickcallback. So the error is thrown.In the first case,
deferredcatches it and considers that that resulting promise in in failed state. Thedeferreddocumentation states that if you want it to effectively throw an error that pushed the promise into failed state, you have to calldoneSee https://github.com/medikoo/deferred#ending-chain for documentation