Mastering Promises

Published by Brayan K

A Promise is a JavaScript object representing the eventual result of an asynchronous operation, starting in a pending state and later settling as either fulfilled with a value or rejected with an error.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Follow the promise returned by each step

A promise represents one eventual outcome. A handler does not change a successful number into a different number inside the original promise: then returns a new promise for the result of that handler. Start by tracing the value that each step returns. These examples use local values and controlled callbacks; none requests a remote service.

const original = Promise.resolve(" 4 ");
const parsed = original.then(text => Number(text.trim())); // A new promise.
const doubled = parsed.then(number => number * 2); // Receives parsed's value.
console.log(original === parsed);
console.log(await original);
console.log(await parsed);
console.log(await doubled);

// ✅ Expected output:
// false
//  4 
// 4
// 8

The original string remains the original promise’s fulfillment value. Each handler is called asynchronously, even when its input is already fulfilled. Event Loop, Microtasks & Async Internals owns the exact scheduling examples; this lesson owns how values and failures travel through the chain.

Construction, resolution and settlement are different events

console.log("before");
const promise = new Promise(resolve => {
  console.log("executor");
  resolve(3);
  console.log("after resolve");
});
promise.then(value => console.log("handler", value));
console.log("after construction");
await promise;

// ✅ Expected output:
// before
// executor
// after resolve
// after construction
// handler 3

Calling resolve chooses an outcome; it does not stop the surrounding function. Use return if execution should leave that callback. Only the first call of the resolving functions has an effect. There is a further distinction: resolving with another pending promise adopts its eventual outcome, so resolved does not always mean fulfilled already.

let finish;
const inner = new Promise(resolve => { finish = resolve; });
const outer = new Promise((resolve, reject) => {
  resolve(inner);
  reject(new Error("ignored later call"));
});
let observed = false;
const result = outer.then(value => { observed = true; return value; });
await Promise.resolve();
console.log("observed before release", observed);
finish(7);
console.log(await result, observed);

// ✅ Expected output:
// observed before release false
// 7 true

The first resolve locks outer onto inner; the later reject does not override it. There is no portable synchronous state getter used here: observed records whether our handler has run. A pending promise is not automatically a background job and does not itself cancel the work that might settle it.

const promise = new Promise(() => 42);
let observed = false;
promise.then(() => { observed = true; });
await Promise.resolve();
console.log("handler ran", observed);

// ✅ Expected output:
// handler ran false

This program deliberately does not await the never-settled promise. The constructor ignores its executor’s return value. That also makes an async executor a bad bridge: its returned promise is ignored, and a rejection after await does not settle the outer promise. Keep the executor synchronous and call resolve or reject from the callback you are adapting.

A handler must return the work that belongs in its chain

const missing = Promise.resolve(5).then(value => { value * 2; });
const returned = Promise.resolve(5).then(value => { return value * 2; });
console.log(await missing);
console.log(await returned);

// ✅ Expected output:
// undefined
// 10

Braces create a function body, not an implicit return. A missing return can be intentional for a side effect, but the next handler then receives undefined. Return a promise when the next step depends on its completion; the chain adopts that promise rather than giving the next handler a promise nested inside a promise.

let finish;
const work = new Promise(resolve => { finish = resolve; });
const chain = Promise.resolve("start").then(() => work).then(value => value + "!");
let observed = false;
const complete = chain.then(value => { observed = true; return value; });
await Promise.resolve();
console.log(observed);
finish("ready");
console.log(await complete);

// ✅ Expected output:
// false
// ready!
function double(value) {
  console.log("double called", value);
  return value * 2;
}
const mistaken = Promise.resolve(3).then(double(9));
console.log("attached");
console.log(await mistaken);
console.log(await Promise.resolve(3).then(double));

// ✅ Expected output:
// double called 9
// attached
// 3
// double called 3
// 6

double(9) executes while the argument is evaluated. Its numeric return is not a handler, so then passes the original fulfillment value through. Pass a function reference, or a function that calls your operation with the argument it needs. Callbacks & Callback Hell owns callback arguments and function-versus-call mistakes.

Recovery belongs to the returned branch

const reason = new Error("missing");
const recovered = Promise.reject(reason).catch(() => "fallback");
const swallowed = Promise.reject(reason).catch(() => {});
const propagated = Promise.reject(reason).catch(error => { throw error; });
console.log(await recovered);
console.log(await swallowed);
try { await propagated; } catch (error) { console.log(error === reason); }

// ✅ Expected output:
// fallback
// undefined
// true

A catch that only logs and returns nothing converts that branch into a fulfilled undefined value. That is recovery, even if the message looked like an error. Return a deliberate fallback when it satisfies the caller’s contract; otherwise throw the same error or a meaningful replacement.

const events = [];
const chain = Promise.resolve(1).then(
  () => { throw new Error("transform failed"); },
  () => { events.push("same then rejection"); }
).catch(error => { events.push(error.message); });
await chain;
console.log(events.join(" | "));

// ✅ Expected output:
// transform failed

The two callbacks passed to one then handle the outcome of its input promise. A throw in the fulfillment callback rejects the newly returned promise, which a later catch can handle.

const source = Promise.resolve(2);
const bad = source.then(() => { throw new Error("bad branch"); });
const good = source.then(value => value + 1);
const handled = bad.catch(error => error.message);
const [goodResult, handledResult, originalBad] = await Promise.allSettled([good, handled, bad]);
console.log(goodResult.value);
console.log(handledResult.value);
console.log(originalBad.status, originalBad.reason.message);

// ✅ Expected output:
// 3
// bad branch
// rejected bad branch

Every returned promise has its own outcome. Here all branches have observers, including bad; the example does not create an unhandled rejection to teach a predictable result. Promise Combinators (all, race, allSettled, any) owns the full rules for coordinating multiple promises.

await Promise.resolve("value").then(() => {
  throw new RangeError("quantity must be at most 20");
});

// ✅ Expected error:
// RangeError: quantity must be at most 20

Finally observes cleanup, not replacement data

console.log(await Promise.resolve(4).finally(() => 99));
const original = new Error("operation failed");
try {
  await Promise.reject(original).finally(() => {});
} catch (error) {
  console.log(error === original);
}
try {
  await Promise.resolve(4).finally(() => { throw new Error("cleanup failed"); });
} catch (error) {
  console.log(error.message);
}

// ✅ Expected output:
// 4
// true
// cleanup failed

finally receives no fulfillment value or rejection reason. If it finishes normally, the returned chain keeps the prior outcome. If cleanup throws or returns a rejected promise, the chain rejects with that failure. It can also delay continuation while a returned cleanup promise is pending. Observe the promise returned by finally; it is a new branch too.

Wrap callback APIs at their boundary

Use new Promise when an API reports completion through callbacks and does not already return a promise. The constructor catches a synchronous throw while calling the executor. It cannot catch an exception thrown later in an independently scheduled callback; catch conversion errors inside that callback and call reject.

function readValue(register) {
  return new Promise((resolve, reject) => {
    register((error, text) => {
      if (error != null) { reject(error); return; }
      try { resolve(JSON.parse(text)); }
      catch (parseError) { reject(parseError); }
    });
  });
}
const value = await readValue(callback => queueMicrotask(() => callback(null, '{"count":2}')));
console.log(value.count);
try {
  await readValue(callback => queueMicrotask(() => callback(null, "{")));
} catch (error) {
  console.log(error.name);
}
const reason = new Error("registration failed");
try { await readValue(() => { throw reason; }); }
catch (error) { console.log(error === reason); }

// ✅ Expected output:
// 2
// SyntaxError
// true

The JSON syntax error is printed by name because message wording varies between engines. This bridge does not add retries, cancellation or a timeout. Those are separate contracts, not automatic promise features. Async/Await owns consuming a promise with await; AbortController & Cancelling Async Work owns cooperation with an abort signal.

Guided exercise: keep a two-step transformation connected

Fill each blank using its literal hint. The first handler must return the promise from lookup, the second must return the selected name, and the final observer must await the connected chain.

const lookup = id => Promise.resolve({ id, name: "Mina" });
const name = Promise.resolve("u1")
  .then(id => { ___ lookup(id); }) // 👉 replace ___ with return
  .then(user => user.___); // 👉 replace ___ with name
console.log(___ name); // 👉 replace ___ with await

// ✅ Expected output:
// Mina

Independent brief: adapt a one-shot quantity callback

Implement readQuantity(register). register receives a callback(error, text) and may call it immediately, later, or more than once. The first callback invocation wins. A non-null/undefined error rejects with the exact same value; a successful text must be a canonical decimal string from 0 to 20, with no sign, spaces or leading zero except "0". Invalid text rejects with RangeError("quantity must be a canonical integer from 0 to 20"). A synchronous registration throw must reject if no earlier outcome has won. Return a promise on every call; a non-function register must reject with TypeError("register must be a function").

Check valid zero and twenty, asynchronous success, leading zero, whitespace, negative, excessive and non-string values; error identity; first-callback wins; and a synchronous registration failure. Do not add retries or claim that rejecting cancels the callback source.

function readQuantity(register) {
  return new Promise((resolve, reject) => {
    if (typeof register !== "function") throw new TypeError("register must be a function");
    let called = false;
    register((error, text) => {
      if (called) return;
      called = true;
      if (error != null) { reject(error); return; }
      try {
        if (typeof text !== "string" || !/^(0|[1-9]\d*)$/.test(text) || Number(text) > 20) {
          throw new RangeError("quantity must be a canonical integer from 0 to 20");
        }
        resolve(Number(text));
      } catch (conversionError) {
        reject(conversionError);
      }
    });
  });
}
for (const value of ["0", "20"]) {
  console.log(await readQuantity(done => done(null, value)));
}
console.log(await readQuantity(done => queueMicrotask(() => done(null, "7"))));
for (const value of ["01", " 1", "-1", "21", 2]) {
  try { await readQuantity(done => queueMicrotask(() => done(null, value))); }
  catch (error) { console.log(error.name, error.message); }
}
const reason = new Error("source failed");
try { await readQuantity(done => done(reason)); }
catch (error) { console.log("same error", error === reason); }
console.log(await readQuantity(done => {
  done(null, "4");
  done(null, "9");
  throw new Error("too late");
}));
try { await readQuantity(done => { done(null, "bad"); done(null, "3"); }); }
catch (error) { console.log("first invalid wins", error instanceof RangeError); }
try { await readQuantity(() => { throw reason; }); }
catch (error) { console.log("registration", error === reason); }
try { await readQuantity(null); }
catch (error) { console.log(error.name, error.message); }

// ✅ Expected output:
// 0
// 20
// 7
// RangeError quantity must be a canonical integer from 0 to 20
// RangeError quantity must be a canonical integer from 0 to 20
// RangeError quantity must be a canonical integer from 0 to 20
// RangeError quantity must be a canonical integer from 0 to 20
// RangeError quantity must be a canonical integer from 0 to 20
// same error true
// 4
// first invalid wins true
// registration true
// TypeError register must be a function

Reference notes

The Promise constructor reference documents executor and resolution behaviour. The then reference and finally reference specify how returned promises obtain their outcomes. The examples above exercise those rules with complete local programs.

Practice quiz

What does this complete program print? console.log(await Promise.resolve(3).then(n => n + 2));

  • 5
  • 3
  • undefined
  • Promise

Answer: 5. The returned value fulfills the promise returned by then.

What does this complete program print? console.log(await Promise.resolve(3).then(n => { n + 2; }));

  • 5
  • undefined
  • 3
  • null

Answer: undefined. A block body without return fulfills with undefined.

What does this complete program print? console.log(await Promise.reject("bad").catch(() => "fixed"));

  • bad
  • undefined
  • fixed
  • Rejected

Answer: fixed. Returning a value from catch recovers this branch.

What does this complete program print? console.log(await Promise.resolve(2).finally(() => 8));

  • 8
  • undefined
  • 10
  • 2

Answer: 2. A normal finally return is ignored and preserves the previous fulfillment.

What does this complete program print? const events = []; const p = new Promise(resolve => { events.push("executor"); resolve(); }); p.then(() => events.push("handler")); events.push("sync"); await p; console.log(events.join(","));

  • executor,sync,handler
  • executor,handler,sync
  • sync,executor,handler
  • handler,executor,sync

Answer: executor,sync,handler. The executor runs during construction; the reaction runs after the current synchronous work yields.

What does this complete program print? console.log(await Promise.resolve(4).then(99));

  • 99
  • 4
  • undefined
  • TypeError

Answer: 4. A non-function fulfillment handler is ignored, passing the value through.

What does this complete program print? try { await Promise.resolve(1).then(() => { throw new Error("new"); }, () => "handled"); } catch (error) { console.log(error.message); }

  • handled
  • 1
  • new
  • undefined

Answer: new. The second argument handles rejection of the input promise, not a throw from the sibling fulfillment handler.

What does this complete program print? const p = Promise.resolve(2); const q = p.then(n => n + 1); console.log(p === q, await p, await q);

  • true 3 3
  • false 3 3
  • true 2 3
  • false 2 3

Answer: false 2 3. then returns a distinct promise; the source outcome remains 2.

Continue this course

Related lessons