0

I am learning to do http calls from node/typescript application. I have the following method, using npm package Axios to do a http get call to a fake api end point.

    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";
    }

When I run the above code, I do see the following console outputs, but no console output from either the then block or the catch block. I dont understand where the control goes.

Output I see:

Entered the method.
nothing worked

What I expect to see:

Entered the method.
inside then //or inside catch

Can someone help me figure out what I am doing wrong here?

1 Answer 1

3

You're assigning your promise to the variable res but not doing anything with it.

You probably want something more like:

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)

Please note that I changed the return type to Promise<string> (which is what you want here since it's async) and I made the function name start with a lower-case letter (camelCase is normally used for variable and function names in JavaScript/TypeScript).

Sign up to request clarification or add additional context in comments.

1 Comment

I will have to do .then().catch() if I want to call this async function from a non-async function right? I tried that and I need to return the data as plain string to the caller of that non-async function. How would I do that? when I add return statements inside .then() or .catch(), I get error "Function lacks ending return statement and return type does not include 'undefined' "

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.