簡體   English   中英

res.end 不停止腳本執行

[英]res.end not stopping script from executing

我目前正在嘗試圍繞第 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'
            });
        }
    }
});

或者,您可以在getModelInfo調用之后使用then ,並且只有在getModelInfo不拒絕時才會調用該代碼。

它也應該有一個成功塊。

 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).then(function (response) { return res.send(JSON.stringify({ 'success': true, 'res': response })); }).catch(function (error) { if (error.response && error.response.status === 406) { return res.send(JSON.stringify({ 'success': false, 'reason': 'exceeded_daily_attempts' })); } }); //it will console log console.log('This still gets called even after 406 error;'); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM