Telerik blogs

You probably get the basics of a JavaScript promise. Let’s go even deeper to understand what happens in what order when a promise resolves.

To understand how a JavaScript promise settles, first let’s start with understanding basics of promises.

In JavaScript, a Promise is an object that represents a value that is not available yet, but is expected to become available sometime in the future. At any given moment, a promise is always in exactly one of three states:

  • pending – The promise has not settled yet.
  • fulfilled – The promise has settled successfully with a value.
  • rejected – The promise has settled unsuccessfully with a reason.

You read these properties inside callback functions. Let’s create a very simple promise to return a user.

function loadUser(id) {
    return new Promise((resolve, reject) => {
      console.log('pending');
      if (!id) {
        console.log('rejected');
        reject(new Error('id is required'));
        return;
      }
  
      setTimeout(() => {
        console.log('fulfilled');
        resolve({ id, name: 'DJ' });
      }, 100);
    });
  }

The loadUser function returns a promise, and you use three callback functions to handle the promise’s three possible states, as shown below:

 loadUser(1)
  .then((user) => {
    console.log('ok:', user.name);
  })
  .catch((error) => {
    console.error('failed:', error.message);
  })
  .finally(() => {
    console.log('promise settled');
  });

When you call loadUser(1), the returned promise initially remains in the pending state. It stays pending while the asynchronous operation is in progress. Once the timeout completes, the promise is fulfilled with the user object, and the fulfillment callback passed to .then() is executed.

When you call loadUser(null), the promise is rejected immediately. There is no need to wait for the timeout because the executor detects the invalid input and calls reject() in the same turn in which the executor runs. You can then handle the rejection with .catch().

We use three callback functions to handle different promise states.

  • .then() handles a fulfilled promise.
  • .catch() handles a rejected promise.
  • .finally() runs after the promise settles, whether it was fulfilled or rejected.

Many developers understand about promises up to here. Their mental model is:

Diagram showing pending going to either fulfilled or rejected

Then we learn:

promise goes to either then or catch, and those direct to finally

This is enough to use a Promise, but not enough to understand it at a deeper level, leverage its full power or debug unexpected issues.

Let’s once again understand the behavior when we call loadUser with null.

loadUser(null)
.then((user) => {
  console.log('ok:', user.name);
})
.catch((error) => {
  console.error('failed:', error.message);
})
.finally(() => {
  console.log('promise settled');
});

As you examine the output, loadUser(null):

  • Prints pending
  • Then rejected
  • Then failed: id is required, then promise settled

The executor runs immediately, so pending appears first. null is treated as missing, so it logs rejected and rejects with id is required before the timer can run. The .then callback is skipped, .catch prints failed: id is required, and .finally still runs and prints promise settled.

And when we call loadUser() with valid number 1:

loadUser(1)
.then((user) => {
  console.log('ok:', user.name);
})
.catch((error) => {
  console.error('failed:', error.message);
})
.finally(() => {
  console.log('promise settled');
});

As you examine the output, loadUser(1):

  • Prints pending right away
  • Then, about 100 ms later, it prints fulfilled
  • Then it prints ok: DJ
  • And promise settled

The executor sees a real id, so it does not reject. The timer calls resolve with { id: 1, name: 'DJ' }, .then prints ok: DJ, .catch is skipped, and .finally still runs and prints promise settled.

For a promise, settlement is one-shot. Once it becomes either fulfilled or rejected, its outcome is permanently fixed. Any later call to resolve() or reject() has no effect. Similarly, if the promise has already settled, a later throw inside the same executor cannot change its state. A Promise can settle only once.

Now that we have a basic understanding of promises, you may feel comfortable using them. However, as you go deeper, several interesting questions start to arise.

  • Does resolve() immediately fulfill a promise?
  • Why does code after resolve() still execute?
  • Why does .then() run later even when the promise is already fulfilled?
  • What happens if resolve() is called twice?
  • What happens if we call resolve() and then reject()?
  • Why can a promise be resolved but still pending?
  • What happens when a promise is resolved with another promise?
  • What exactly is a thenable?
  • Why does returning a promise from .then() flatten the chain?
  • How do errors move through a promise chain?

The key is to separate three concepts that are often mixed together:

 

  • Resolution
  • Settlement
  • Reaction scheduling

Once these three concepts become clear, JavaScript promises become much easier to reason about. Let’s start with understanding three states.

The Three States

A promise can be in one of three observable states:

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

A promise is always in exactly one of these states. JavaScript does not expose its current state through a property such as promise.state. Instead, you observe the state through the behavior of its handlers.

  • pending – Since the operation is still in progress, the result is not available yet, so .then() and .catch() have not run.
  • fulfilled – Since the operation completed successfully, the promise has a value, which is passed to .then(onFulfilled).
  • rejected – The promise has a reason (usually an error) that the operation failed, which is passed to .catch(onRejected).

Pending goes either to fulfilled, which goes to then(value) and on to finally, or to rejected, which goes to catch(reason) and on to finally

As you see in the diagram, .catch() and .finally() are both built on top of .then(), but they serve different purposes.

The .catch() is a shortcut for rejection handling and the .then() can accept two callbacks: one for fulfillment and one for rejection.

promise.then(onFulfilled, onRejected);

The .catch() only provides the rejection handler:

promise.catch(onRejected);

So, the two syntaxes below do the same thing.

promise.catch(onRejected);
promise.then(undefined, onRejected);

If the promise is fulfilled, there is no onFulfilled callback here, so its value simply passes through the chain. If the promise is rejected, onRejected runs with the rejection reason.

The .finally() runs regardless of the outcome. We should use .finally() when we need to perform some cleanup or final action whether the promise is fulfilled or rejected:

promise.finally(() => {
  console.log('settled');
});

The onFinally callback receives no arguments. It does not receive the fulfilled value or the rejection reason. After finally() completes, the original value or rejection reason continues through the chain.

The exception is when onFinally itself throws an error or returns a rejected promise. In that case, the chain becomes rejected with that new error.

A newly created promise always starts as pending, and from pending it can become fulfilled or it can become rejected. You fulfill it by calling resolve with an ordinary value.

const promise = new Promise((resolve) => {
  resolve('Hello');
});

promise.then((value) => {
  console.log('state: fulfilled');
  console.log('value:', value);
});

state: fulfilled; value: Hello

You reject a promise by calling reject.

const promise = new Promise((resolve, reject) => {
  reject(new Error('Something failed'));
});

promise.catch((error) => {
  console.log('state: rejected');
  console.log('reason:', error.message);
});

state: rejected; reason: Something failed

As discussed earlier, settlement is one-shot. A fulfilled promise stays fulfilled. A rejected promise stays rejected. There is no path back to pending, and no path from one settled state to the other.

const promise = new Promise((resolve, reject) => {
  resolve('Hello');
  reject(new Error('Something failed')); // already fulfilled
  resolve('Goodbye');                    // already fulfilled
});

promise.then(
  (value) => console.log('fulfilled:', value),
  (error) => console.log('rejected:', error.message)
);

The first resolve('Hello') settled it. The later reject and the later resolve still run as function calls. They do not change the promise. A fulfilled promise stays fulfilled. A rejected promise stays rejected.

Executor Is Synchronous

When we create a promise, the function passed to its constructor is called the executor. The executor receives two functions, resolve and reject, which we call to settle the Promise.These executors are synchronous in nature. To understand that, let’s consider the example:

function question1() {
    console.log('A');
  
    const p = new Promise((resolve, reject) => {
      console.log('B');
      resolve('first');
      resolve('second');
      reject('nope');
      throw new Error('boom');
    });
  
    p.then(
      (value) => console.log('fulfilled:', value),
      (error) => console.log('rejected:', error.message || error)
    );
  
    console.log('C');
  }

  question1();

You should get the expected output as shown below:

A; B; C; fulfilled: first

The output above is due to the executor’s synchronous nature, and the why of the above output can be explained more with the points:

A - B - C is the synchronous turn.

  • console.log('A') runs first.
  • new Promise(...) immediately executes its executor, so B runs on the same call stack.
  • The promise constructor then returns.
  • .then() schedules a microtask; it does not execute the callback immediately.
  • Therefore, C is printed next.

First Settle Wins

The first call that settles a promise determines its final state. Here, resolve('first') fulfills the promise, so its state becomes fulfilled.

  • Once the promise is fulfilled, its state cannot change again.
  • resolve('second') is ignored because the promise is already fulfilled.
  • reject('nope') is ignored because the promise can no longer transition to rejected.
  • throw new Error('boom') does not change the promise’s state because the executor has already settled it.

A promise can settle only once. Any later resolve, reject or thrown error cannot change that settled state.

Handlers Wait for the Next Microtask

Even if the promise is already fulfilled when .then() is attached, the fulfillment handler does not execute immediately.

  • .then() schedules the handler as a microtask rather than running it synchronously.
  • The current synchronous code must finish first. So C is printed before the .then() callback runs.
  • Microtasks run only after the current synchronous turn completes, before the event loop moves on to the next task.

A fulfilled promise can execute its .then() handler later, even though the promise is already settled.

Take another example:

const p = new Promise((resolve, reject) => {
  console.log("A");

  resolve("first");

  console.log("B");

  resolve("second");
  reject("error");

  console.log("C");
});

p.then(value => {
  console.log("Promise:", value);
});

console.log("D");

As handler waits for next microtask, it should print:

A; B; C; Promise: first

Resolved and Still Pending

This is probably the most important concept a JavaScript developer should understand about promises.

A common misunderstanding is to think of resolve(value) as meaning: “The promise is now fulfilled with value.”

That is only true when value is an ordinary, non-promise value. This distinction is at the heart of how promise resolution actually works.

When you resolve an ordinary value, such as a string, a number, an object or undefined, then resolving and settling happen together. The promise becomes fulfilled with that value.

When you resolve another promise, or any object with a .then method, the outer promise locks onto that object. It is resolved. It can still be pending.

Its fate is now “whatever that other promise does.” When the inner promise fulfills, the outer one fulfills with the same value. When the inner promise rejects, the outer one rejects with the same reason.

Let’s understand this with examples:

const promise = new Promise((resolve) => {
  resolve(42);
});

promise.then(
  (value) => console.log('fulfilled:', value),
  (error) => console.log('rejected:', error.message)
);

Here promise is resolved with ordinary non-promise value, so it is fulfilled with the value. Let’s consider another example, where promise is resolved with another promise:

const inner = new Promise((resolve) => { 
  setTimeout(() => { resolve("done"); }, 1000); 
});

const outer = new Promise((resolve) => { 
  resolve(inner); 
  console.log('outer');
});

outer.then(value => console.log(value));

Here, outer promise does not immediately fulfill with the inner promise. Instead, outer adopts the state of inner.

The relationship can be defined as outer follows inner, and as inner is still pending, therefore outer is also effectively waiting.

So, after one second when inner is fulfilled with “done,” then outer is fulfilled with “done.”

Also, resolved does not necessarily mean fulfilled. Consider below example:

let resolveInner;
const inner = new Promise((resolve) => { 
  resolveInner = resolve; 
}); 
const outer = new Promise((resolve) => {
  resolve(inner); 
});

Above, inner is pending and outer is pending, but we can say outer is resolved to the state of inner and it is following the inner. So, outer cannot later do reject(‘something’) because even if it is pending , it is resolved and following the inner.

So, we can say that a promise can be resolved to another pending promise while remaining pending from an observer’s perspective.

The Promise Resolution Procedure

There are two types of resolution:

  1. Resolving an ordinary value
  2. Resolving a promise

As you have read earlier, these types of resolution happen differently. So, when you call:

resolve(value);

JavaScript does not simply ask, “Is value truthy?” or “Should I mark this fulfilled?” Instead, it performs a process commonly described as the Promise Resolution Procedure.

A simplified version looks like this:

Promise Resolution Procedure: resolve(value). Is value ordinary? If yes, fulfil with value. If not, is value promise-like? If yes, adopt its eventual state. If not, fulfil with value.

Due to this, resolve(42) and resolve(otherPromise) behave differently. Let’s consider the example below:

const promise = new Promise((resolve) => {
  resolve(42);
});

promise.then(value => {
  console.log(value);
});

It prints 42 and the flow is:

resolve(42) – 42 is ordinary – promise fulfilled – reaction scheduled – .then() handler runs

If you notice the final step, settlement and reaction execution are separate. Let’s consider another example with promise value:

const inner = new Promise((resolve) => {
  setTimeout(() => {
    resolve("hello");
  }, 1000);
});

const outer = new Promise((resolve) => {
  resolve(inner);
});

outer.then(value => {
  console.log(value);
});

Now the flow becomes:

resolve(inner) – inner is a promise – outer adopts inner – inner fulfils with “hello” – outer fulfils with “hello” - .then() logs “hello”

So in the output you get hello printed. It does not print the promise object. This behavior is what makes promise composition possible.

thenable Assimilation

JavaScript does not only understand native promises. It also understands thenables. A thenable is simply an object with a callable then property.

Consider the below example:

const thenable = {
  then(resolve, reject) {
    resolve("hello");
  }
};

Promise.resolve(thenable)
  .then(value => {
    console.log(value);
  });

This is not necessarily a native promise. But JavaScript can treat it as promise-like and prints hello. So conceptually it can be depicted as below:

Promise.resolve(thenable) – find .then() – call then(resolve, reject) – resolve(“hello”) – Promise fulfills

This ability is called thenable assimilation. Let’s see one more example.

const thenable = {
  then(resolve, reject) {
    resolve("first");
    resolve("second");
    reject("third");
  }
};

Promise.resolve(thenable)
  .then(value => {
    console.log(value);
  });

You should get output first printed, because JavaScript promise allows only the first effective call to win. The later calls cannot change it. For the thenable, the resulting promise maintains its one-shot semantics.

Sometimes, thenable can throw an error. Consider the example below.

const thenable = {
  then() {
    throw new Error("boom");
  }
};
  
Promise.resolve(thenable)
  .catch(error => {
    console.log(error.message);
  });

A thrown exception during thenable processing results in rejection. Consider another example:

const thenable = {
    then() {
      throw new Error("boom");
    }
  };
  
  Promise.resolve(thenable)
    .catch(error => {
      console.log(error.message);
    });

You should get boom printed successfully. The later exception cannot change the output because, for promises, the first effective output wins.

.then() Handler Is Asynchronous

One important concept we need to keep in mind is that the .then() handler is always asynchronous. To understand it better, consider the below example:

const promise = Promise.resolve("done");

console.log("A");

promise.then(value => {
  console.log("B", value);
});

console.log("C");

You should get expected output as shown below:

A; C; B done

This happens even though the promise was already fulfilled before .then() was attached, because promise reactions are scheduled as microtasks.

The promise may already be settled, but the handler does not suddenly execute in the middle of the current synchronous execution. It can be depicted as below:

Current synchronous execution – attach .then() – queue reaction – continue current code – current stack finishes – microtask runs – .then() handler executes

I hope this article has helped you understand, beyond the basics, how JavaScript actually resolves a promise and what happens under the hood.

Thanks for reading!


Dhananjay Kumar
About the Author

Dhananjay Kumar

Dhananjay Kumar is the founder of nomadcoder, an AI-driven developer community and training platform in India. Through nomadcoder, he organizes leading tech conferences such as ng-India and AI-India. He partners with startups to rapidly build MVPs and ship production-ready applications. His expertise spans Angular, modern web architecture and AI agents, and he is available for training, consulting or product acceleration from Angular to API to agents.

Related Posts

Comments

Comments are disabled in preview mode.