ai js async 2026-10-29
write a tutorial of js async await
(ai answer)
JavaScript async/await Tutorial
async/await is syntax that makes asynchronous code look and behave more like synchronous code. It is built on Promises.
Basic Syntax
Mark a function as async. Inside it, use await to pause until a Promise resolves.
async function fetchData() { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; }
asyncfunctions always return a Promise.awaitcan only be used insideasyncfunctions (or at the top level in modules).
Simple Example
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function example() { console.log('Start'); await delay(1000); console.log('After 1 second'); return 'Done'; } example().then(result => console.log(result)); // Output: // Start // (1 second later) // After 1 second // Done
Error Handling
Use try/catch (like synchronous code):
async function getUser(id) { try { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error('User not found'); return await response.json(); } catch (error) { console.error('Failed:', error.message); return null; } }
Running Multiple Operations
Sequential (one after another):
const user = await getUser(1); const posts = await getPosts(user.id);
Parallel (faster when independent):
const [user, posts] = await Promise.all([ getUser(1), getPosts(1) ]);
Key Points
- Prefer
async/awaitover.then()chains for readability. - Always handle errors with
try/catchor.catch()on the returned Promise. - Avoid blocking the main thread—long CPU work still needs Web Workers or similar.
- Top-level
awaitworks in ES modules:const data = await fetchData();
That’s the core. Practice by rewriting Promise-based code with async/await.