JavaScript Promises

Interactive examples of JavaScript Promises in action

Promise Chaining

Sequential operations using Promise chains

This example simulates fetching a user, then their posts, then the comments on their latest post.

// Promise chaining example
// Step 1: Fetch user data
fetchUser(userId)
  .then(user => {
    console.log(`✅ Fetched user: ${user.name}`);
    // Step 2: Use the user ID to fetch their posts
    return fetchPosts(user.id);  // Return a new promise
  })
  .then(posts => {
    console.log(`✅ Fetched ${posts.length} posts`);
    console.log(`Latest post: ${posts.latest.title}`);
    // Step 3: Use the latest post ID to fetch comments
    return fetchComments(posts[0].id);  // Return another promise
  })
  .then(comments => {
    console.log(`✅ Fetched ${comments.length} comments on latest post`);
    console.log(`Sample comment: ${comments[0]}`);
    // Chain complete!
  })
  .catch(error => {
    // Any error in the chain is caught here
    console.error(`Error: ${error.message}`);
  });
// Async/await version of the promise chain
async function fetchUserData(userId) {
  try {
    // Step 1: Fetch user data
    const user = await fetchUser(userId);
    console.log(`✅ Fetched user: ${user.name}`);
    
    // Step 2: Use the user ID to fetch their posts
    const posts = await fetchPosts(user.id);
    console.log(`✅ Fetched ${posts.length} posts`);
    console.log(`Latest post: ${posts.latest.title}`);
    
    // Step 3: Use the latest post ID to fetch comments
    const comments = await fetchComments(posts[0].id);
    console.log(`✅ Fetched ${comments.length} comments on latest post`);
    console.log(`Sample comment: ${comments[0]}`);
    
    // All operations complete!
    return comments;
  } catch (error) {
    // Any error in the sequence is caught here
    console.error(`Error: ${error.message}`);
  }
}

// Call the async function
fetchUserData(userId);
1
Fetching User
2
Fetching Posts
3
Fetching Comments

Promise.all

Run multiple promises in parallel

This example simulates fetching data from three different API endpoints simultaneously.

// Promise.all example - run multiple promises in parallel
// Create an array of promises
const promises = [
  fetchWeatherData(),    // Promise 1: Weather API
  fetchStockPrices(),    // Promise 2: Stock API
  fetchNewsHeadlines()   // Promise 3: News API
];

// Wait for all promises to resolve
Promise.all(promises)
  .then(results => {
    // results is an array containing the resolved values
    // in the same order as the promises array
    const [weather, stocks, news] = results;
    
    console.log(`Weather: ${weather.condition}`);
    console.log(`Stock: $${stocks.price}`);
    console.log(`News: ${news.headlines.map(headline => `"${headline}"`).join("\n ")}`);
    
    // All data is available at the same time!
  })
  .catch(error => {
    // If ANY promise rejects, the catch block is triggered
    console.error(`One of the requests failed: ${error.message}`);
  });
// Async/await version of Promise.all
async function fetchAllData() {
  try {
    // Create an array of promises
    const promises = [
      fetchWeatherData(),    // Promise 1: Weather API
      fetchStockPrices(),    // Promise 2: Stock API
      fetchNewsHeadlines()   // Promise 3: News API
    ];
    
    // Wait for all promises to resolve with await
    const results = await Promise.all(promises);
    
    // Destructure the results array
    const [weather, stocks, news] = results;
    
    console.log(`Weather: ${weather.condition}`);
    console.log(`Stock: $${stocks.price}`);
    console.log(`News: ${news.headlines.map(headline => `"${headline}"`).join("\n ")}`);
    
    // All data is available at the same time!
    return results;
  } catch (error) {
    // If ANY promise rejects, the catch block is triggered
    console.error(`One of the requests failed: ${error.message}`);
  }
}

// Call the async function
fetchAllData();
Weather API
Stock API
News API

Promise Rejection

Handling errors with Promises

This example demonstrates how to handle rejected promises using catch() and try/catch with async/await.

// Using .catch() with promise chains
fetchData(endpoint)
  .then(data => {
    console.log('Success:', data);
  })
  .catch(error => {
    // Handle any errors that occurred
    console.error('Error with .catch():', error.message);
  });
// Using try/catch with async/await
async function fetchDataSafely() {
  try {
    // await lets us use promises with try/catch
    const data = await fetchData(endpoint);
    console.log('Success:', data);
  } catch (error) {
    // Handle any errors that occurred
    console.error('Error with try/catch:', error.message);
  }
}

// Call the async function
fetchDataSafely();

Using .catch()

Using try/catch