async and await are modern JavaScript features that simplify working with Promises, making asynchronous code look and behave more like synchronous code. They help you write cleaner, more readable logic for tasks like fetching data from APIs, waiting for timers, or handling long-running operations.
async function always returns a Promise, even if you explicitly return a normal value.await pauses the execution of an async function until a Promise settles (resolves or rejects).await and handle errors using try...catch.async/await is built on top of Promises – it’s just a nicer syntax, not a separate feature.To declare an asynchronous function, use the async keyword before the function definition. Inside that function, you can use await in front of any expression that returns a Promise.
Key rules:
await can only be used inside an async function (in normal JavaScript files).await line and can be caught in a try...catch block.A simple async function that returns a value. JavaScript wraps this value in a Promise.
async function myFunction() {
return "Hello!";
}
myFunction().then(alert); // Alerts "Hello!"
Here, await pauses the function until fetch() and then response.json() are completed.
async function fetchData() {
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log(data);
}
This example uses a Promise that resolves after 2 seconds using setTimeout(), then awaits it.
function delay() {
return new Promise(resolve => {
setTimeout(() => resolve("Done!"), 2000);
});
}
async function run() {
console.log("Waiting...");
let result = await delay();
console.log(result); // "Done!"
}
run();
Use try...catch inside an async function to handle rejected Promises.
async function loadData() {
try {
let response = await fetch("https://invalid-url.com");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error:", error.message);
}
}
An async function returns a Promise, so you can still use .then() on it if you want.
async function getUser() {
return "John";
}
getUser().then(alert); // Alerts "John"
Click the button to run an async function that simulates loading data with a delay.
Click the button to see the async/await flow.
"Waiting..." immediately.delay(), which returns a Promise that resolves after 2 seconds.await delay() pauses the run() function until the Promise resolves."Done!" and that value is logged.This pattern is common when:
.then() chains (“Promise hell”).async/await to make complex asynchronous flows easier to read and debug.await calls in try...catch to handle errors gracefully.await can be used with any function that returns a Promise.await outside an async function in normal scripts – it will cause a syntax error.await in front of a Promise-based call if you need to pause for its result.async function that fetches a post from an API (for example, https://jsonplaceholder.typicode.com/posts/1) and logs only the title.setTimeout() inside a Promise and use await to delay execution by a few seconds.fetch(), then catch and log the error using try...catch inside an async function.