Script Valley
JavaScript Tutorial for Beginners to Advanced
Async JavaScript: Promises, Async/Await, and Fetch APILesson 7.2

Async/Await in JavaScript

async functions, await keyword, try/catch with async/await, parallel async calls, async iteration

Async/Await in JavaScript

Async/await is syntactic sugar built on top of Promises. It allows you to write asynchronous code that reads like synchronous code, making it far easier to understand and maintain. Any function declared with the async keyword automatically returns a Promise.

The async and await Keywords

async function fetchUser(id) {
  // This function always returns a Promise
  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  const user = await response.json();
  return user;
}

// Call an async function
fetchUser(1).then(user => console.log(user));

Error Handling with try/catch

async function getWeather(city) {
  try {
    const response = await fetch(`https://api.example.com/weather?city=${city}`);

    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Failed to fetch weather:', error.message);
    return null;
  }
}

async function main() {
  const weather = await getWeather('London');
  if (weather) {
    console.log(`Temperature: ${weather.temp}°C`);
  }
}

main();

Running Async Operations in Parallel

async function fetchMultiple() {
  try {
    // Sequential — one waits for the other
    // const user = await fetchUser(1);
    // const posts = await fetchPosts(1);

    // Parallel — both run simultaneously
    const [user, posts] = await Promise.all([
      fetch('https://jsonplaceholder.typicode.com/users/1').then(r => r.json()),
      fetch('https://jsonplaceholder.typicode.com/posts?userId=1').then(r => r.json())
    ]);

    console.log('User:', user.name);
    console.log('Post count:', posts.length);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchMultiple();

Up next

The Fetch API and HTTP Requests

Sign in to track progress