Using Q.promises: how to catch an async throw?

雨燕双飞 提交于 2019-11-26 18:35:40

问题


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.

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?


回答1:


The exception in the setTimeout is not related anyhow to the promises, you have to catch that yourself using a try-catch-block.

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));


来源:https://stackoverflow.com/questions/15504429/using-q-promises-how-to-catch-an-async-throw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!