错误处理尝试&赶上+回调?

时间:2012-08-30 18:28:23

标签: javascript error-handling

  

可能重复:
  Is it possible to catch exceptions thrown in a JavaScript async callback?

我从数据库中提取订单然后请求,我希望能够打破forEach并且我可以使用trycatch执行此操作,但我认为回调不起作用

try{
    orders.find().forEach(function(order){
        request({
            "method":"get",
            "json":true
        },function (error, response, data){
            if (!error && response.statusCode == 200) {
                console.log("Order id "+order.id);
            }else{
                throw "limit";
            }
        });
    });
}catch(err){
    if(err == "limit"){
        console.log("error occured");
    }
}

这就是我得到的

    /Users/thomas/Desktop/forerunner/retrieveTransactions.js:120
                throw "limit";
                ^
    limit

我只想:

    error occured

1 个答案:

答案 0 :(得分:5)

您需要在回调函数中添加try-catch,例如:

orders.find().forEach(function(order){
    request({
        "method":"get",
        "json":truetry{
    },function (error, response, data){
        try{
            if (!error && response.statusCode == 200) {
                console.log("Order id "+order.id);
            }else{
              throw "limit";
            }
        }catch(err){
            if(err == "limit"){
                console.log("error occured");
            }
        }
    });
});