【问题标题】:Executing statements after a successful asynchronous request in a try/catch block在 try/catch 块中成功异步请求后执行语句
【发布时间】:2019-03-04 23:10:07
【问题描述】:

我想了解为什么在异步网络请求成功后 console.log 语句不会输出到终端。我理解为什么如果请求失败它不会执行,因为执行会跳转到 catch 块。但是,在完成成功请求后,我看不到日志记录语句的痕迹。我有以下代码:

function processRequest (url, res) {
    return axios.get(url).then(response => {
        res.send({status: 'PASS', message: `${response.status}, on ${url}`});
    });
}

app.post('/api', async (req, res) => {
    let response;
    try {
        response = await processRequest(someValidURL, res);
        console.log('after request'); //this statement does not show up after successful request
    } catch (error) {
      console.error(error);
    }

}

为了尽量减少这篇文章,我没有包含 express 和 axios 库的 require 语句以及 express 设置代码。任何帮助表示赞赏。

【问题讨论】:

    标签: javascript express asynchronous async-await try-catch


    【解决方案1】:

    那是因为您正在从processRequest 中返回响应,这意味着您的请求处理已在此处完成并已发送响应。

    要实现你想要做的事情,你应该这样做

    function processRequest (url) {
        return axios.get(url);
    }
    
    app.post('/api', async (req, res) => {
        let response;
        try {
            response = await processRequest(someValidURL);
            console.log('after request', response);
            res.send({status: 'PASS', message: `${response.status}, on ${url}`}); 
        } catch (error) {
          console.error(error);
            res.send({status: 'ERROR'});
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2021-11-17
      • 2015-08-26
      • 1970-01-01
      • 2014-09-09
      相关资源
      最近更新 更多