可能重复:
Is it possible to catch exceptions thrown in a JavaScript async callback?
我从数据库中提取订单然后请求,我希望能够打破forEach
并且我可以使用try
和catch
执行此操作,但我认为回调不起作用
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
答案 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");
}
}
});
});