The await keyword is used inside asynchronous functions (with [async]) to wait for a Promise to complete. It “stops” function execution until the Promise completes, and returns the Promise result. This makes asynchronous code look like synchronous code.
// Asynchronous function with await
async function fetchData() {
console.log('Starting download...');
const response = await fetch('/api/data'); // Wait for response
const data = await response.json(); // Wait for parsing
return data;
}
// Usage
fetchData().then(result => console.log(result));The [await] keyword is like an airport dispatcher telling a plane: “Wait until the runway is ready, then you can take off”. [await] makes code wait for an asynchronous operation to complete without blocking the entire site! ✈️
The [await] keyword can only be used inside asynchronous functions (with [async]). It waits for a Promise to complete and returns its result:
async function example() {
console.log('Start');
// Wait 2 seconds
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('2 seconds passed');
return 'Done';
}async function getUserData() {
try {
const response = await fetch('/api/user');
const userData = await response.json();
return userData;
} catch (error) {
console.log('Loading error:', error);
}
}async function stepByStep() {
console.log('1. Start');
const result1 = await Promise.resolve('First result');
console.log('2.', result1);
const result2 = await Promise.resolve('Second result');
console.log('3.', result2);
console.log('4. End');
}
stepByStep();
// Output:
// 1. Start
// 2. First result
// 3. Second result
// 4. Endasync function asyncTask() {
console.log('Task started');
await new Promise(resolve => setTimeout(resolve, 3000));
console.log('Task completed');
}
console.log('1. Start');
asyncTask(); // Starts execution, but doesn't block
console.log('2. Continue'); // Executes immediately
console.log('3. End'); // Executes immediately
// After 3 seconds: 'Task completed'// Instead of .then() chains
// fetch('/api/data')
// .then(response => response.json())
// .then(data => processData(data))
// .then(result => console.log(result))
// .catch(error => console.log(error));
// With await code is cleaner
async function handleData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
const result = processData(data);
console.log(result);
} catch (error) {
console.log('Error:', error);
}
}async function sequentialOperations() {
const user = await fetchUser();
const posts = await fetchUserPosts(user.id);
const comments = await fetchPostComments(posts[0].id);
return { user, posts, comments };
}// ❌ Error — await outside async function
// function bad() {
// const result = await somePromise(); // SyntaxError!
// }
// ✅ Correctly
async function good() {
const result = await somePromise(); // Works!
}// ❌ Error — error not handled
// async function risky() {
// const data = await fetch('/api/data');
// // If fetch fails, error will "fall" up
// }
// ✅ Correctly — error handling
async function safe() {
try {
const data = await fetch('/api/data');
} catch (error) {
console.log('Error:', error);
}
}The [await] keyword is a powerful tool for working with asynchronous operations, making code more readable and understandable! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪