使用 Q.promises:如何捕捉异步抛出? [英] Using Q.promises: how to catch an async throw?
本文介绍了使用 Q.promises:如何捕捉异步抛出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将 Q 用于 Promise,但是在设置一些测试时,我发现我发现了捕获在返回 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
并链接一个 fail
和或如下一个 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
中的异常无论如何与承诺无关,您必须使用 try<自己捕获它/code>-
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屋!
查看全文