延迟方法中不会抛出错误
Error is not thrown inside a deferred method
有人可以向我解释为什么我的第一个示例没有抛出错误吗?为什么我使用 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()
中抛出错误 ...
任何解释将不胜感激。
谢谢
我看过这个post (No errors thrown/displayed when in a deferred callback)。但它只给出了一半的答案......
deferred
的行为在我看来是合理的。
在第二种情况下,我认为 deferred
没有办法捕获 nextTick
回调中抛出的错误。所以报错了。
在第一种情况下,deferred
捕获它并认为导致的承诺处于失败状态。 deferred
文档指出,如果你想让它有效地抛出一个将 promise 推入失败状态的错误,你必须调用 done
deferred.resolve().then(function(){
console.log('deferred resolved');
throw new Error('Synchronous error thrown in deferred.then()');
}).done();
有人可以向我解释为什么我的第一个示例没有抛出错误吗?为什么我使用 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()
中抛出错误 ...
任何解释将不胜感激。 谢谢
我看过这个post (No errors thrown/displayed when in a deferred callback)。但它只给出了一半的答案......
deferred
的行为在我看来是合理的。
在第二种情况下,我认为 deferred
没有办法捕获 nextTick
回调中抛出的错误。所以报错了。
在第一种情况下,deferred
捕获它并认为导致的承诺处于失败状态。 deferred
文档指出,如果你想让它有效地抛出一个将 promise 推入失败状态的错误,你必须调用 done
deferred.resolve().then(function(){
console.log('deferred resolved');
throw new Error('Synchronous error thrown in deferred.then()');
}).done();