JAVASCRIPT

JavaScript Promises: Syntax, Usage, and Examples

JavaScript promises handle asynchronous operations, making it easier to work with APIs, databases, and other tasks that take time to complete. A promise represents a value that may be available now, in the future, or never. Instead of using callback functions, promises provide a cleaner and more manageable way to handle asynchronous operations.


How to Use JavaScript Promises

A JavaScript promise has three states:

  • Pending – The operation is still in progress.
  • Fulfilled – The operation completed successfully.
  • Rejected – The operation failed.

Creating a Promise

You can create a promise using the Promise constructor:

const myPromise = new Promise((resolve, reject) => {
  let success = true;

  if (success) {
    resolve("Operation successful!");
  } else {
    reject("Something went wrong.");
  }
});

This promise either resolves successfully or rejects based on a condition.

Handling Resolved and Rejected Promises

Once a promise is created, you can handle its result using .then() and .catch():

myPromise
  .then((result) => {
    console.log(result); // "Operation successful!"
  })
  .catch((error) => {
    console.error(error); // If rejected, this runs
  });

JavaScript Promises then() Method

The .then() method runs when a promise is resolved. You can chain multiple .then() calls to perform sequential operations:

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

When to Use JavaScript Promises

Promises simplify working with asynchronous operations. Here are some common use cases:

  1. Fetching data from an API – Promises handle API requests that take time to return data.
  2. Reading files – If a script needs to read a file, promises ensure that the next operation waits for the file to load.
  3. Waiting for multiple operations – When multiple asynchronous functions need to complete before continuing, promises help structure the code.
  4. Chaining dependent operations – Promises allow sequential execution of functions that depend on previous results.
  5. Handling animations or timed events – Promises make it easier to delay or trigger animations at the right moment.

Examples of JavaScript Promises

Fetching Data from an API

fetch("https://jsonplaceholder.typicode.com/users/1")
  .then((response) => response.json())
  .then((user) => console.log(user.name))
  .catch((error) => console.error("Error fetching user:", error));

Resolving a Promise After a Delay

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

delay(2000).then(() => console.log("Executed after 2 seconds"));

JavaScript Chain Promises

You can chain multiple .then() calls when one promise depends on another:

function fetchUser() {
  return fetch("https://jsonplaceholder.typicode.com/users/1").then((response) =>
    response.json()
  );
}

function fetchPosts(userId) {
  return fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`).then(
    (response) => response.json()
  );
}

fetchUser()
  .then((user) => fetchPosts(user.id))
  .then((posts) => console.log("User posts:", posts))
  .catch((error) => console.error("Error:", error));

Learn More About JavaScript Promises

Are JavaScript Promises Asynchronous?

Yes, promises run asynchronously, meaning JavaScript continues executing other code while waiting for a promise to resolve.

console.log("Start");

setTimeout(() => console.log("Timeout callback"), 0);

Promise.resolve().then(() => console.log("Promise resolved"));

console.log("End");

This outputs:

Start
End
Promise resolved
Timeout callback

Promises execute before setTimeout callbacks but after synchronous code.

Async/Await and Promises in JavaScript

The async and await keywords make working with promises easier by allowing you to write asynchronous code that looks synchronous.

async function fetchData() {
  try {
    let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}

fetchData();

Instead of chaining .then(), await pauses execution until the promise resolves.

Await Multiple Promises in JavaScript

If you need to wait for multiple promises, use Promise.all().

const promise1 = fetch("https://jsonplaceholder.typicode.com/users/1").then((res) => res.json());
const promise2 = fetch("https://jsonplaceholder.typicode.com/posts/1").then((res) => res.json());

Promise.all([promise1, promise2])
  .then((values) => console.log("User and post:", values))
  .catch((error) => console.error("Error fetching data:", error));

This waits for both promises to resolve before executing the .then() block.

Concurrent Promises in JavaScript

If you want the first resolved promise to return immediately, use Promise.race().

const slow = new Promise((resolve) => setTimeout(() => resolve("Slow"), 3000));
const fast = new Promise((resolve) => setTimeout(() => resolve("Fast"), 1000));

Promise.race([slow, fast]).then((winner) => console.log("Winner:", winner));

Since fast resolves first, it prints "Winner: Fast".

Array of Promises in JavaScript

If you have an array of promises and want to execute them one after another, use reduce().

const urls = [
  "https://jsonplaceholder.typicode.com/posts/1",
  "https://jsonplaceholder.typicode.com/posts/2",
  "https://jsonplaceholder.typicode.com/posts/3",
];

urls
  .reduce(
    (chain, url) => chain.then(() => fetch(url).then((res) => res.json()).then(console.log)),
    Promise.resolve()
  )
  .catch(console.error);

Each request starts only after the previous one finishes.


JavaScript promises help manage asynchronous operations efficiently. They allow you to write cleaner, more structured code when dealing with API requests, file operations, and event-based programming.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH