Error is not thrown inside a deferred method

怎甘沉沦 提交于 2019-12-25 00:30:32

问题


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:


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



来源:https://stackoverflow.com/questions/30983382/error-is-not-thrown-inside-a-deferred-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!