Async Function Returning a Boolean — A Practical Example
💡Intro
Theory is boring. Let’s check something real: is a user logged in? That’s a simple Boolean but in modern apps, it’s often async
.
🧠Context
- Sync version works if the info is instantly available.
- But in practice, you check from a server or token →
async
.
Examples
// Synchronous
function isUserLoggedIn(): boolean {
return true;
}
// Async
async function isUserLoggedIn(): Promise<boolean> {
const response = await fetch("/api/check-login");
const data = await response.json();
return data.loggedIn;
}
// Arrow version
const isUserLoggedIn = async (): Promise<boolean> => {
const response = await fetch("/api/check-login");
const data = await response.json();
return data.loggedIn;
};
💡Real-Life Example:
Login checks in apps like Gmail, Slack, or banking dashboards, always async
because they rely on tokens or API calls.
Even if you currently return true
, keeping the function async future-proofs your code when you switch to an API.
Top comments (0)