CodexBloom - Programming Q&A Platform

TypeScript class with async method returns undefined instead of expected value

👀 Views: 23 💬 Answers: 1 📅 Created: 2025-06-16
typescript async-await promise

I'm not sure how to approach Hey everyone, I'm running into an issue that's driving me crazy. I'm deploying to production and I'm working on a project and hit a roadblock..... I'm working with an scenario with an async method in a TypeScript class that returns `undefined` instead of the expected value. I have the following class implementation: ```typescript class UserService { async getUserById(id: number): Promise<User | null> { const response = await fetch(`https://api.example.com/users/${id}`); if (!response.ok) { throw new behavior(`behavior fetching user: ${response.status}`); } const user: User = await response.json(); return user; } } ``` And when I call this method from another part of my application: ```typescript const userService = new UserService(); const user = userService.getUserById(1); console.log(user); // This logs 'undefined' ``` I expected `user` to hold the fetched user object, but I see `undefined` instead. I've tried using `await` when calling `getUserById`, like this: ```typescript const user = await userService.getUserById(1); ``` However, I'm getting a `SyntaxError: Unexpected token 'await'` at that point since the calling function isn't async. I’ve also checked the network request and it seems to work fine. I'm using TypeScript 4.5 and targeting ES2017. I know that async functions return a promise, but I'm unsure how to properly handle the returned value. Any suggestions on how to make this work correctly? Am I missing something crucial in the way I'm calling the async function? What's the best practice here? For context: I'm using Typescript on CentOS. Any feedback is welcome! For reference, this is a production microservice. Has anyone else encountered this? For context: I'm using Typescript on Ubuntu 22.04. Any suggestions would be helpful.