【问题标题】:simple typescript function with axios get call does not work带有 axios get 调用的简单打字稿功能不起作用
【发布时间】:2020-07-29 05:16:41
【问题描述】:

我正在学习从节点/打字稿应用程序进行 http 调用。我有以下方法,使用npm package Axios 对假的api 端点进行http get 调用。

    public GetTrailById(trailId: number) : string {
        console.log("Entered the method.");
        const res = axios.get("https://reqres.in/api/users?page=2")
        .then((res: { data: any; }) => {
            console.log("inside then");
            return "this is good, got response";
        })
        .catch((err: { response: any; }) => {
            console.log("inside catch");
            return "this is not good, inner catch";
        });
        console.log("nothing worked");
        return "nothing worked";
    }

当我运行上述代码时,我确实看到了以下控制台输出,但没有来自 then 块或 catch 块的控制台输出。我不明白控件的去向。

我看到的输出:

Entered the method.
nothing worked

我期望看到的:

Entered the method.
inside then //or inside catch

有人可以帮我弄清楚我在这里做错了什么吗?

【问题讨论】:

    标签: node.js typescript http axios


    【解决方案1】:

    您将您的承诺分配给变量res,但没有对它做任何事情。

    你可能想要更多类似的东西:

    async function getTrailById(trailId: number): Promise<string> {
        console.log("Entered the method.");
        try {
          const res = await axios.get("https://reqres.in/api/users?page=2");
          console.log("inside then");
          return res.data;
        } catch {
          console.log("inside catch");
          return "this is not good, inner catch";
        }
    }
    
    // ...in some other async function
    const trail = await getTrailById(trailId)
    

    请注意,我将返回类型更改为Promise&lt;string&gt;(这是您想要的,因为它是异步的)并且我使函数名称以小写字母开头(camelCase 通常用于变量和函数名称JavaScript/TypeScript)。

    【讨论】:

    • 如果我想从非异步函数调用此异步函数,我将不得不做.then().catch(),对吗?我试过了,我需要将数据作为纯字符串返回给该非异步函数的调用者。我该怎么做?当我在 .then() 或 .catch() 中添加返回语句时,我收到错误“函数缺少结束返回语句并且返回类型不包括‘未定义’”
    猜你喜欢
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2017-04-13
    • 2014-05-06
    • 1970-01-01
    相关资源
    最近更新 更多