错误处理尝试&赶上+回调? [英] Error-handling try & catch + callback?
本文介绍了错误处理尝试&赶上+回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要从数据库中提取订单,然后请求,我希望能够打破 forEach
,并且可以通过 try
和 catch来做到这一点.
,但我认为回调无法正常工作
I am pulling orders from a database and then requesting, I want to be able to break the forEach
and I can do that with a try
and catch
but I think that the callback isn't working
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
推荐答案
您需要在回调函数中添加try-catch,例如:
You need to add try-catch inside the callback function, something like:
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");
}
}
});
});
这篇关于错误处理尝试&赶上+回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文