Codectionary / Developer documentation / JavaScript

Promises

A Promise represents a value that may not be available yet - the eventual result of an asynchronous operation. It exists in one of three states: pending, fulfilled, or rejected. then() handles a successful result, catch() handles an error, and finally() runs regardless of outcome. Promises are the foundation that async/await is built on top of.

Syntax

new Promise((resolve, reject) => { })
promise.then(onSuccess).catch(onError)

Examples

Creating and Using a Promise

Wrapping an asynchronous operation in a Promise.

function fetchUserData(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (userId > 0) {
        resolve({ id: userId, name: "Alice" });
      } else {
        reject(new Error("Invalid user ID"));
      }
    }, 1000);
  });
}

fetchUserData(1)
  .then(user => console.log(user))
  .catch(error => console.log(error.message));

Chaining Promises

Each then() returns a new promise, allowing sequential operations.

fetch("/api/user/1")
  .then(response => response.json())
  .then(user => {
    console.log("User:", user.name);
    return fetch(`/api/posts/${user.id}`);
  })
  .then(response => response.json())
  .then(posts => console.log("Posts:", posts))
  .catch(error => console.log("Something failed:", error.message))
  .finally(() => console.log("Request cycle complete"));

Best practices

  • Always add a .catch() to handle rejected promises - an unhandled rejection can silently fail or crash depending on the environment
  • Return a value or another promise from inside .then() when chaining, so the next .then() receives the right data
  • Prefer async/await over long .then() chains in most cases - it reads more like familiar synchronous code
  • Use .finally() for cleanup logic (hiding a spinner, closing a connection) that should run whether the promise succeeds or fails

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading