1. What is async/await
?
async/await
is a modern way to handle asynchronous code in JavaScript. It’s built on Promises but makes code look synchronous, easier to read, and easier to maintain.
async
function: Declares a function as asynchronous. It always returns a Promise.await
: Pauses the execution of anasync
function until the Promise resolves (or rejects).
2. Basic Syntax
async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}
fetchData();
Explanation:
async function fetchData()
→ marks the function as asynchronous.await fetch(...)
→ waits for the fetch to complete before moving on.await response.json()
→ waits for the JSON parsing.- Execution inside
fetchData()
pauses at eachawait
.
3. async/await
vs Promises
Promise version:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
async/await
version:
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
getData();
✅ Advantages of async/await
:
- Code reads top-to-bottom (like synchronous code).
- Easier to handle multiple sequential async operations.
try/catch
works for error handling (cleaner than.catch()
chains).
4. Handling Errors
Use try/catch
inside async
functions:
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('Network error');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
getData();
5. Running Multiple Async Tasks
You can run multiple async operations in parallel using Promise.all
:
async function fetchMultiple() {
const urls = ['api1', 'api2', 'api3'];
const promises = urls.map(url => fetch(url).then(res => res.json()));
const results = await Promise.all(promises);
console.log(results);
}
fetchMultiple();
✅ This is faster than awaiting each fetch one by one.
6. Key Rules
await
can only be used insideasync
functions (or top-level in modern environments).async
functions always return a Promise.await
pauses execution inside the function, but doesn’t block the whole program.
7. Quick Example
Simulate a delay:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function greet() {
console.log('Hello');
await delay(1000); // wait 1 second
console.log('World!');
}
greet();
// Output: "Hello" → waits 1 second → "World!"