
Thodoris Kouleris
Software Engineer

async - await
What is async - await
Asynchronous programming is one of the most important concepts in modern JavaScript development. It allows your code to perform tasks without blocking the execution of other operations — making apps faster and more responsive.
Traditionally, developers used callbacks and later Promises to handle asynchronous tasks like network requests or file operations. However, both approaches can sometimes make the code harder to read. This is where async and await come in.
async: A keyword used to declare that a function is asynchronous. When you mark a function with async, it automatically returns a Promise, even if you don’t explicitly return one.
await: A keyword that pauses the execution of an async function until the Promise is resolved (or rejected). It makes asynchronous code look and behave like synchronous code.
Together, async and await simplify working with Promises and make your code cleaner, easier to read, and easier to debug.
Real World Analogy
Imagine you are at a coffee shop. You order your coffee. While the barista is preparing it, you don’t just stand there doing nothing — you check your phone, read emails, or chat with a friend. When the coffee is ready, the barista calls your name, and you pick it up.
Placing the order is like calling an async function. The Promise is the preperation time. While waiting for your coffee you do other tasks - non blocking asynchronous execution. You await for the coffee to be ready, and when ready you pick it up and go on with your life.
Example in Javascript
// A function that simulates fetching data from an API
function fetchUserData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ id: 1, name: "Alice" });
}, 2000); // simulating network delay
});
}
// Async function using await
async function displayUser() {
console.log("Fetching user data...");
// Wait until the promise is resolved
const user = await fetchUserData();
console.log("User fetched:", user);
console.log("Done!");
}
// Call the async function
displayUser();
console.log("This runs while waiting for the data...");
The function displayUser() starts running and logs on console the "Fetching user data..." text. The function pauses at await fetchUserData() while the Promise is pending. This does not stop the rest of the code. While you wait for the async function to finish the rest of the code will be executed so you will see on you console "This runs while waiting for the data...". After about 2 seconds the Promise will be resolved and the user will be logged on you console.
The async and await keywords provide a cleaner way to handle asynchronous code in JavaScript. They let you write code that looks synchronous but still takes full advantage of asynchronous operations.
Whenever you’re working with APIs, databases, or any time-consuming tasks, async/await is the modern, elegant solution to keep your code both efficient and easy to understand.