What is async/await in JavaScript
async and await are syntactic sugar over promises, introduced in ES2017, which allows writing asynchronous code as if it were synchronous.
async— makes function asynchronous, automatically returning Promise.await— pauses execution insideasyncfunction until promise completes (successfully or with error).
Simple Example
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function greet() {
console.log("Waiting...");
await delay(1000); // Wait 1 second
console.log("Hello after 1 second!");
}
greet();
async: How Does it Work?
async function foo() {
return 42;
}
foo().then(result => console.log(result)); // 42
Even if function returns simple value,
asyncwraps it inPromise.
await: How Does it Work?
async function fetchUser() {
const res = await fetch("/user.json");
const data = await res.json();
return data;
}
awaitpauses execution untilfetchreturns result.- After completion, result is passed to variable and execution continues.
Error Handling
With async/await it's convenient to use try/catch:
async function getData() {
try {
const response = await fetch("/api");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("An error occurred:", error);
}
}
Features
awaitcan only be used inside async function.awaitonly works with promises (or any thenable objects).- If
awaitreturns error, it's thrown and caught incatch.
Summary
async/awaitmakes asynchronous code understandable, linear and clean.- It doesn't replace promises, but simplifies their use.
- Always handle errors with
try/catchor.catch().
Good to Know:
await doesn't block main thread! It only pauses current async function execution, freeing thread for other tasks.