有人可以向我解释为什么我的错误不会出现在我的第一个例子中吗?为什么我使用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)。但它只给出了一半答案......
答案 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();