Loading...
Loading...
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 inside async function until promise completes (successfully or with error).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 function foo() {
return 42;
}
foo().then(result => console.log(result)); // 42
Even if function returns simple value,
asyncwraps it inPromise.
async function fetchUser() {
const res = await fetch("/user.json");
const data = await res.json();
return data;
}
await pauses execution until fetch returns result.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);
}
}
await can only be used inside async function.await only works with promises (or any thenable objects).await returns error, it's thrown and caught in catch.async/await makes asynchronous code understandable, linear and clean.try/catch or .catch().Good to Know:
await doesn't block main thread! It only pauses current async function execution, freeing thread for other tasks.