【问题标题】:Why is my catch statement triggering even though the .then is resolved?为什么即使 .then 已解决,我的 catch 语句仍会触发?
【发布时间】:2021-11-13 03:36:12
【问题描述】:

这是我目前在我的服务器文件夹中的代码。我只是想知道由于某种原因,即使 .then 语句主动发送响应,但由于 res.send 有效并向用户发送响应,catch 控制台日志仍在发送?

const express = require("express");
const router = express.Router();
const { API_KEY, API_URL } = process.env
const axios = require("axios")

router.get("/", async (req, res) => {
    console.log(API_URL + API_KEY)
    await axios.get(API_URL + API_KEY + "&count=9")
        .then((response) => {
            res.send(response.data)
        })
        .catch(
            console.log("error")
        )
})

module.exports = router

谢谢!

【问题讨论】:

    标签: javascript express axios


    【解决方案1】:

    .catch 接受 回调 - 现在,您正在立即调用 console.log 并将结果传递给 .catch。这个:

    // ...
    .catch(console.log("error"))
    

    等价于

    const consoleResult = console.log("error");
    // ...
    .catch(consoleResult)
    

    你需要改成

    .catch(
        () => {
            console.log("error")
        }
    )
    

    或者,更好的是,检查参数以查看错误是什么:

    .catch(
        (error) => {
            console.log("error:", error.message)
        }
    )
    

    【讨论】:

    • 哦,明白了,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2021-04-05
    相关资源
    最近更新 更多