使用Q.promises:如何捕获异步抛出? [英] Using Q.promises: how to catch an async throw?
本文介绍了使用Q.promises:如何捕获异步抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Q作为promises,但是在设置一些测试时,我发现我看到了捕获在返回promise的函数内抛出异步错误的方法。
I'm using Q for promises, but when setting up some tests I discover I see way in catching async errors thrown inside a function that returns a promise.
我试图把它包装在一个 Q.when
中并链接一个失败
和或低于 Q.fcall
和链式失败
,但我无法得到它工作。
I tried to wrap it inside a Q.when
and chained a fail
and or as below a Q.fcall
and a chained fail
,but I can't get it to work.
var func = function(){
var deferred = Q.defer();
setTimeout(function(){
throw new Error("async error");
},100);
return deferred.promise;
}
Q.fcall(func)
.then(function(){
console.log("success");
})
.fail(function(err){
console.log(err);
})
有没有办法解决这个问题?
Is there a way to to this?
推荐答案
setTimeout
中的异常无论如何都与承诺无关,你必须自己使用尝试
- catch
-block。
The exception in the setTimeout
is not related anyhow to the promises, you have to catch that yourself using a try
-catch
-block.
或者您使用 Q.delay
:
Or you use Q.delay
:
function func(){
return Q.delay(100).then(function(){
throw new Error("async error");
});
}
func()
.then(console.log.bind(console, "success"))
.fail(console.log.bind(console));
这篇关于使用Q.promises:如何捕获异步抛出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文