Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Promises and Async

The Promise object

Reference for the JavaScript Promise constructor: the executor, resolve and reject, the pending, fulfilled and rejected states, and common mistakes.

A Promise represents a value that is not available yet. It is always in one of three states: pending (still working), fulfilled (finished with a value) or rejected (failed with a reason). Once a promise leaves the pending state it is settled and can never change again.

You create a promise with new Promise(executor). The executor runs immediately and synchronously, and receives two functions, resolve and reject, which you call when the work is done. Consumers attach handlers with then(), catch() and finally(), or use await.

JavaScript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve("done"), 100);
});

Try it

JS States and settling

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Wrapping a callback API

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
new Promise(executor)

executor(resolve, reject)
Name Description
executor A function called immediately with resolve and reject. Its return value is ignored.
resolve(value) Resolves the promise. A normal value fulfills it. If value is another promise or thenable, this promise follows it.
reject(reason) Rejects the promise with reason, usually an Error.

Return value: the constructor returns a new promise object, and must be called with new.

Exceptions: calling Promise(...) without new throws a TypeError, and so does passing something that is not a function. An error thrown inside the executor does not escape; it rejects the promise (unless it already settled).

Usage notes

  • Only the first call counts. After the first resolve() or reject(), further calls are ignored.
  • The executor is synchronous. Handlers always run later, as microtasks, even for a promise that is already settled.
  • Resolved is not the same as fulfilled. A promise resolved with another pending promise is still pending, locked in to follow that other one.
  • Reject with an Error. Error objects carry a stack trace; plain strings do not.
  • Unhandled rejections. A rejected promise nobody handles triggers an unhandledrejection event in browsers and can end a Node.js process.
  • Do not wrap promises in promises. If a function already returns a promise, return it; do not write new Promise((res) => res(other)).
  • async functions always return promises and are usually easier to read than manual construction.
  • Promises cannot be cancelled. Use an AbortController to stop the underlying work.

Browser support

Promise is supported by every current browser and Node.js.