The async and await keywords simplify working with promises in JavaScript by making asynchronous code look and behave more like synchronous code.

💡 What is async/await?
async marks a function as asynchronous, returning a promise. await pauses the function execution until the awaited promise resolves or rejects.
Using async Functions
Declare a function with async. It implicitly returns a promise, even if you return a non-promise value.
📌 Deep Dive: async function example
async function greet() {
return 'Hello!';
}
greet().then(console.log); // Logs: Hello!
Using await to Pause for Promises
await can only be used inside async functions. It waits for a promise to resolve and returns its value.
📌 Deep Dive: await example
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function delayedMessage() {
console.log('Waiting...');
await delay(1000);
console.log('1 second passed');
}
delayedMessage();
Benefits of async/await vs. Promises
| Feature | async/await | Promise chaining |
|---|---|---|
| Readability | More like synchronous code, easier to read | Nested or chained, can get complex |
| Error handling | Use try/catch blocks | Use .catch() |
| Sequential operations | Use multiple await statements | Chain promises |
| Parallel operations | Use Promise.all with await | Use Promise.all() |
Error Handling with async/await
Use try/catch inside async functions to handle rejected promises.
📌 Deep Dive: Error handling
async function fetchData() {
try {
const response = await fetch('https://does-not-exist.example');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error occurred:', error.message);
}
}
fetchData();
⚠️ Important
Do not use await outside of async functions; it will cause a syntax error. For top-level await, modern environments support it but check compatibility.
Summary
asyncfunctions always return a promise.awaitpauses async function execution until a promise settles.- Use try/catch to handle errors in async functions.
- async/await improves code clarity over promise chaining.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does the async keyword do when added to a function?
Question 2 of 2
Where can you use the await keyword?
Loading results...