While .then() chains can get messy, async and await make your code look clean and readable.
1. The async Keyword
You must label a function as async before you can use the await keyword inside it. An async function always returns a Promise.
2. The await Keyword
This keyword tells JavaScript: "Pause execution of this function until this promise is resolved, then give me the result." Crucially, it doesn't freeze the whole browser—just that specific function.
3. Why use it?
It eliminates "Promise Chaining" and makes it much easier to read variables from several asynchronous calls at once.
The Code Example
// A "fake" function that acts like a slow database
const getUsername = () => {
return new Promise((resolve) => {
setTimeout(() => resolve("Coder_Gemini"), 1500);
});
};
// 1. Defining the Async function
async function displayUser() {
console.log("Loading user...");
// 2. Using 'await' to wait for the result
// The code "pauses" here until the promise resolves
const name = await getUsername();
console.log(`Welcome back, ${name}!`);
}
displayUser();
// 3. Real world Fetch example (Fetching from an API)
async function getGithubProfile(user) {
const response = await fetch(`https://api.github.com/users/${user}`);
const data = await response.json(); // Wait for JSON parsing
console.log(data.name, data.bio);
}
getGithubProfile("google");