以下是使用 Q 的 Promise 的简短示例。
这是 test1.js:
function testDefer() {
var deferred = Q.defer();
fs.readFile("foo.txt", "utf-8", function (error, text) {
if (error) {
deferred.reject(new Error(error));
} else {
deferred.resolve(text);
}
});
return deferred.promise;
}
这是 test2.js
(function(){
'use strict';
var test1 = require('./test1');
test1.testDefer().then(
function(data){
console.log('all good');
},
function(err) {
//upon error i might want to throw an exception, however, it is not thrown / ignored.
throw new Error('I want to throw this exception');
}
);
})();
我想在 test2 中抛出异常,以防承诺被拒绝(或者在某些情况下当它被解决时)。无论如何,异常都会被忽略,并且程序会在不引发异常的情况下完成。
我的问题是,如何从成功/失败函数中抛出错误?
谢谢
所有错误都在then
处理程序被抓住并被用来拒绝由此产生的承诺。你想要的是done method:
很像then
,但在未处理的情况下有不同的行为
拒绝。如果存在未处理的拒绝,要么是因为promise
被拒绝并且没有onRejected
提供了回调,或者
因为onFulfilled
or onRejected
抛出错误或返回
被拒绝的承诺,所产生的拒绝原因被作为
事件循环的未来回合中出现异常。
此方法应用于终止承诺链
不能传递到其他地方。由于抛出异常then
回调
被消耗并转化为拒绝,最后的异常
链条很容易被无意中、默默地忽略。通过安排
在事件循环的未来一轮中抛出的异常,以便
它不会被抓住,它会导致onerror
浏览器上的事件window
, or an uncaughtException
Node.js 上的事件process
目的。
黄金法则done
vs. then
用法是:要么return
你的
向其他人承诺,或者如果链条以你结束,请致电done
到
终止它。
Q.ninvoke(fs, "readfile", "foo.txt", "utf-8").done(function(data){
console.log('all good');
}, function(err) {
throw new Error('I want to throw this exception');
}); // or omit the error handler, and 'err' will be thrown
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)