What is Async Await in JavaScript: Simple Explanation and Example
async and await are keywords that help write asynchronous code in a way that looks and behaves like synchronous code. async marks a function to return a promise, and await pauses the function execution until the promise resolves, making code easier to read and manage.How It Works
Imagine you are cooking dinner and waiting for water to boil. Instead of standing and watching the pot, you do other tasks and come back when the water is ready. This is similar to how async and await work in JavaScript.
An async function always returns a promise. Inside this function, you can use await to pause the code until a promise finishes, like waiting for the water to boil. This pause only affects the async function, not the whole program, so other code can keep running.
This makes asynchronous code easier to write and understand because it looks like normal step-by-step code, but it still handles tasks that take time, like fetching data from the internet.
Example
This example shows an async function that waits for a promise to resolve using await. It simulates a delay and then prints a message.
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function greet() { console.log('Waiting...'); await delay(1000); // wait for 1 second console.log('Hello after 1 second!'); } greet();
When to Use
Use async and await when you need to handle tasks that take time, like fetching data from a server, reading files, or waiting for timers. They help you write code that waits for these tasks to finish without blocking the whole program.
For example, when building a website that loads user information from the internet, async and await let you write clear code that waits for the data before showing it, improving user experience and code readability.
Key Points
asyncmarks a function to return a promise.awaitpauses the function until the promise resolves.- They make asynchronous code easier to read and write.
- Only use
awaitinsideasyncfunctions. - They help avoid complex promise chains and callbacks.
Key Takeaways
async to declare functions that return promises.await inside async functions to wait for promises to resolve.await only works inside async functions.