延迟方法中不会抛出错误

时间:2015-06-22 15:02:53

标签: node.js exception-handling deferred

有人可以向我解释为什么我的错误不会出现在我的第一个例子中吗?为什么我使用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()');
    });
});

为什么我需要等待nextTick在then() ...

中抛出错误

任何解释将不胜感激。 THX

我看过这篇文章(No errors thrown/displayed when in a deferred callback)。但它只给出了一半答案......

1 个答案:

答案 0 :(得分:1)

deferred的行为在你的案件中对我来说似乎是合理的。

在第二种情况下,我不认为deferred有办法捕捉nextTick回调中引发的错误。所以错误就会被抛出。

在第一种情况下,deferred捕获它并认为导致失败状态的承诺。 deferred文档说明如果您希望它有效地抛出将承诺推入失败状态的错误,则必须调用done

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

请参阅https://github.com/medikoo/deferred#ending-chain了解文档