Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...