javascript - res.end 不停止脚本执行
问题描述
我目前正在尝试围绕第 3 方 API 构建 API,但是在我的 Express 路由中,我似乎无法让当前脚本停止执行,这是我的代码:
app.get('/submit/:imei', async function (req, res) {
//configure
res.setHeader('Content-Type', 'application/json');
MyUserAgent = UserAgent.getRandom();
axios.defaults.withCredentials = true;
const model_info = await getModelInfo(req.params.imei).catch(function (error) {
if(error.response && error.response.status === 406) {
return res.send(JSON.stringify({
'success': false,
'reason': 'exceeded_daily_attempts'
}));
}
});
console.log('This still gets called even after 406 error!');
});
如果初始请求返回406错误,如何停止执行脚本?
解决方案
如果您不想在捕获错误后执行代码,那么您应该这样做:
app.get('/submit/:imei', async function (req, res) {
//configure
res.setHeader('Content-Type', 'application/json');
MyUserAgent = UserAgent.getRandom();
axios.defaults.withCredentials = true;
try {
const model_info = await getModelInfo(req.params.imei);
console.log('This will not get called if there is an error in getModelInfo');
res.send({ success: true });
} catch(error) {
if(error.response && error.response.status === 406) {
return res.send({
'success': false,
'reason': 'exceeded_daily_attempts'
});
}
}
});
或者,您可以在通话then
后使用,只有在不拒绝getModelInfo
时才会调用该代码。getModelInfo
推荐阅读
- java - RabbitMQ - 如何使用 DefaultConsumer 从消费者标签中提取消息体?
- angularjs - 在 AngularJS SPA 中提供 index.html 后,如何有条件地重定向?
- javascript - 选择匹配元素中的一个元素
- sql - 使用其他表中的值显示字段值
- linux-kernel - 让 PCIe 设备驱动程序处理来自同一 FPGA 设备的同一 IRQ 行中的不同中断
- c# - asp .net 核心 wcf 端点
- html - 第二次尝试在主屏幕中添加 Web 应用时提示无法正常工作
- ethereum - 通过来自不同合约的自动生成的 getter 访问变量
- vba - 根据excel VBA中的条件突出显示值
- junit - 无法将 Cucumber 功能粘合到步骤定义