Promises and Async/Await in JavaScript ES6

6/20/2025

async await in JavaScript ES6 example

Go Back

Promises & Async/Await in JavaScript ES6+: The Complete Guide

Asynchronous programming is essential in modern JavaScript development. Whether you're fetching data from an API or performing background tasks, JavaScript's Promises and Async/Await make asynchronous operations more readable and efficient.

In this guide, we'll explore:

  • What are Promises?

  • How Promises work

  • Common Promise methods

  • Introduction to Async/Await

  • How Async/Await simplifies code

  • Real-world examples

  • Best practices


 async await in JavaScript ES6 example

What is a Promise?

A Promise is an object representing the eventual completion (or failure) of an asynchronous operation.

Syntax:

const promise = new Promise((resolve, reject) => {
  // asynchronous operation
  if (success) {
    resolve('Success!');
  } else {
    reject('Error occurred');
  }
});

📈 Promise States

  1. Pending – Initial state

  2. Fulfilled – Operation completed successfully

  3. Rejected – Operation failed

Handling Promises:

promise
  .then(result => console.log(result))
  .catch(error => console.error(error))
  .finally(() => console.log("Done"));

Real Example: Fetch API with Promises

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Async/Await: Syntactic Sugar Over Promises

Introduced in ES2017, async and await make asynchronous code look and behave more like synchronous code.

Basic Usage:

async function fetchData() {
  try {
    const res = await fetch('https://api.example.com/data');
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

 


When to Use Which?

  • Use Promises when chaining multiple async tasks or using concurrent operations (e.g. Promise.all).

  • Use Async/Await when readability and top-down execution is preferred.


Best Practices

  • Always handle errors using .catch() or try...catch

  • Avoid mixing await with .then() unnecessarily

  • Use Promise.all() or Promise.race() for multiple concurrent requests

Example: Multiple Requests

const urls = ['url1', 'url2'];
const requests = urls.map(url => fetch(url).then(res => res.json()));
Promise.all(requests)
  .then(results => console.log(results))
  .catch(err => console.error(err));

Conclusion

Promises and Async/Await are fundamental to handling asynchronous operations in modern JavaScript. They offer powerful ways to manage operations like API requests, timers, and more.

By mastering them, you’ll write more readable, manageable, and bug-free asynchronous code

 

Table of content