ai js async 2026-10-29

By Xah Lee. Date: .

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;
}

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

That’s the core. Practice by rewriting Promise-based code with async/await.