Skip to content
BENIBIX Learn

Promise (JavaScript)

Development🧭 Programming ParadigmsAsynchronous Code

Also known as Promise, Future, Promises

An object for a result not ready yet. It ends in a value or an error.

Think of it like

Think of it like a ticket at a coat check. It is not your coat yet, but you will get it back.

Example

Lucy's app calls fetch for a weather page. It gets a promise at once, and the forecast shows up when the promise is fulfilled.

Why it matters

Most modern JavaScript tools give back promises. async/await is built on top of them.

Definition

A promise is an object that stands for a result that is not ready yet. It starts as pending, then ends as fulfilled with a value or rejected with an error. You attach what to do next with then, and what to do on failure with catch. Promises can be chained, so steps read in order instead of nesting. Other languages call the same idea a future.

Example code

javascript
Promise.resolve(5).then((n) => console.log(n * 2)); // 10
then runs once the promise has its value.

Common mistake

Forgetting a catch. A rejected promise with no catch can fail without anyone seeing it.

Key takeaways

  1. 1
    A value to come. Not ready yet.
  2. 2
    Three states. Pending, fulfilled, rejected.
  3. 3
    Chain with then. Steps read in order.

Compare