问题
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:
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).
来源:https://stackoverflow.com/questions/61242234/simple-typescript-function-with-axios-get-call-does-not-work