首页 > 解决方案 > 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错误,如何停止执行脚本?

标签: javascriptnode.jsexpress

解决方案


如果您不想在捕获错误后执行代码,那么您应该这样做:

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


推荐阅读