Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Promises and Async/Await in JavaScript

Master asynchronous JavaScript with Promises and async/await syntax. Learn how to handle asynchronous operations elegantly and avoid callback hell.

jiocoder TeamUpdated Jun 6, 20264 min readJavaScript
Promises and Async/Await in JavaScript

What are Promises?#

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Promises provide a cleaner alternative to callbacks for handling asynchronous code. They represent a value that may be available now, in the future, or never.

Promises have three states:

  • Pending - Initial state, neither fulfilled nor rejected
  • Fulfilled - Operation completed successfully
  • Rejected - Operation failed

Once a promise is fulfilled or rejected, it cannot change state. This makes promises predictable and easier to work with than callbacks.

Installation#

Promises are built into modern JavaScript (ES6+). No installation needed for modern browsers and Node.js 12+. For older environments, you can use a polyfill:

Code
npm install es6-promise

Creating Promises#

You can create a promise using the Promise constructor:

Code
const promise = new Promise((resolve, reject) => {
  // Async operation
  setTimeout(() => {
    const success = Math.random() > 0.5;
    if (success) {
      resolve('Operation succeeded');
    } else {
      reject(new Error('Operation failed'));
    }
  }, 1000);
});

promise
  .then(result => {
    console.log('Success:', result);
  })
  .catch(error => {
    console.error('Error:', error.message);
  })
  .finally(() => {
    console.log('Operation completed');
  });

Promise Chaining#

Promises can be chained together for sequential operations:

Code
fetch('/api/user')
  .then(response => response.json())
  .then(user => {
    return fetch(`/api/posts/${user.id}`);
  })
  .then(response => response.json())
  .then(posts => {
    console.log('User posts:', posts);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Promise Methods#

Promise.all() - Wait for all promises to resolve:

Code
const promise1 = fetch('/api/users');
const promise2 = fetch('/api/posts');
const promise3 = fetch('/api/comments');

Promise.all([promise1, promise2, promise3])
  .then(responses => {
    return Promise.all(responses.map(r => r.json()));
  })
  .then(([users, posts, comments]) => {
    console.log('All data loaded:', { users, posts, comments });
  })
  .catch(error => {
    console.error('One or more requests failed:', error);
  });

Promise.race() - Returns the first promise that settles:

Code
const timeout = new Promise((_, reject) => 
  setTimeout(() => reject(new Error('Timeout')), 5000)
);

const fetchData = fetch('/api/data');

Promise.race([fetchData, timeout])
  .then(response => response.json())
  .then(data => console.log('Data:', data))
  .catch(error => console.error('Error:', error));

Promise.allSettled() - Wait for all promises to settle (resolve or reject):

Code
const promises = [
  fetch('/api/users'),
  fetch('/api/posts'),
  fetch('/api/invalid')
];

Promise.allSettled(promises)
  .then(results => {
    results.forEach((result, index) => {
      if (result.status === 'fulfilled') {
        console.log(`Promise ${index} succeeded`, result.value);
      } else {
        console.log(`Promise ${index} failed`, result.reason);
      }
    });
  });

Promise.any() - Returns the first fulfilled promise:

Code
const promise1 = Promise.reject('Error 1');
const promise2 = Promise.resolve('Success 2');
const promise3 = Promise.resolve('Success 3');

Promise.any([promise1, promise2, promise3])
  .then(value => console.log('First success:', value)); // "Success 2"

Async/Await Syntax#

async/await is syntactic sugar over promises, making asynchronous code look synchronous:

Code
async function fetchUserData(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const user = await response.json();
    return user;
  } catch (error) {
    console.error('Error fetching user:', error);
    throw error;
  }
}

// Usage
async function displayUser(userId) {
  try {
    const user = await fetchUserData(userId);
    console.log('User:', user.name);
    return user;
  } catch (error) {
    console.error('Failed to display user:', error);
  }
}

Error Handling with Async/Await#

Error handling is cleaner with async/await:

Code
async function handleData() {
  try {
    const data = await fetchData();
    const processed = await processData(data);
    const saved = await saveData(processed);
    return saved;
  } catch (error) {
    console.error('Error in handleData:', error);
    // Handle error appropriately
    throw error; // Re-throw if needed
  }
}

// Multiple error handling
async function complexOperation() {
  try {
    const step1 = await operation1();
    try {
      const step2 = await operation2(step1);
      return step2;
    } catch (error) {
      console.error('Error in step 2:', error);
      // Fallback for step 2
      return await fallbackOperation();
    }
  } catch (error) {
    console.error('Error in step 1:', error);
    throw error;
  }
}

Parallel Execution#

Execute multiple async operations in parallel:

Code
// Sequential (slow)
async function sequential() {
  const user = await fetchUser();
  const posts = await fetchPosts();
  const comments = await fetchComments();
  return { user, posts, comments };
}

// Parallel (fast)
async function parallel() {
  const [user, posts, comments] = await Promise.all([
    fetchUser(),
    fetchPosts(),
    fetchComments()
  ]);
  return { user, posts, comments };
}

Real-World Example: API Client#

Code
class ApiClient {
  constructor(baseURL) {
    this.baseURL = baseURL;
  }
  
  async request(endpoint, options = {}) {
    try {
      const response = await fetch(`${this.baseURL}${endpoint}`, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers
        },
        ...options
      });
      
      if (!response.ok) {
        throw new Error(`API Error: ${response.status} ${response.statusText}`);
      }
      
      return await response.json();
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }
  
  async get(endpoint) {
    return this.request(endpoint, { method: 'GET' });
  }
  
  async post(endpoint, data) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data)
    });
  }
  
  async put(endpoint, data) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data)
    });
  }
  
  async delete(endpoint) {
    return this.request(endpoint, { method: 'DELETE' });
  }
}

// Usage
const api = new ApiClient('https://api.example.com');

async function loadUserData(userId) {
  try {
    const [user, posts, followers] = await Promise.all([
      api.get(`/users/${userId}`),
      api.get(`/users/${userId}/posts`),
      api.get(`/users/${userId}/followers`)
    ]);
    
    return { user, posts, followers };
  } catch (error) {
    console.error('Failed to load user data:', error);
    throw error;
  }
}

Best Practices#

  • Always handle errors with try/catch or .catch()
  • Use Promise.all() for parallel operations
  • Prefer async/await for readability
  • Don't forget await - missing it returns a Promise
  • Use Promise.allSettled() when you need all results
  • Avoid nesting - use async/await instead
  • Handle timeouts for long-running operations
  • Clean up resources in finally blocks

Common Mistakes#

Code
// ❌ Missing await
async function bad() {
  const data = fetch('/api/data'); // Returns Promise, not data!
  console.log(data); // Promise object
}

// ✅ Correct
async function good() {
  const data = await fetch('/api/data');
  console.log(data); // Actual data
}

// ❌ Not handling errors
async function risky() {
  const data = await fetch('/api/data'); // Can throw!
  return data.json();
}

// ✅ Correct
async function safe() {
  try {
    const data = await fetch('/api/data');
    return await data.json();
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

Promises and async/await are essential tools for modern JavaScript development. They make asynchronous code more readable, maintainable, and easier to debug. Master these concepts, and you'll be able to handle any asynchronous operation with confidence.

Article discussion

(0)

Join the discussion — login to comment and help other developers.

Login to comment