SkillPilotAI

From Callbacks to Promises

Real apps do work that takes time, like loading a user from a server or confirming a payment. JavaScript does not wait for it; callbacks were the first way to handle the result, and Promises replaced them with flat, chainable code and one place for errors.

13.1 What is a callback

  • A callback is a function passed to another function, to be called when the work completes.
  • setTimeout(..., 500) here simulates a slow server.
  • JavaScript does not wait: Start and End print first, the user arrives last.
JavaScript
function getUser(id, callback) {  setTimeout(() => {    callback({ id, name: "Rahul" });  }, 500);} console.log("Start");getUser(1, (user) => {  console.log("User:", user.name);});console.log("End");
Output
StartEndUser: Rahul

13.2 The problem: callback hell

  • Dependent steps (user -> orders -> payment) must each be written inside the previous callback.
  • The code drifts right into a pyramid and the error check repeats at every level.
  • Inversion of control: the other function might call your callback twice or never.
JavaScript
getUser(1, (err, user) => {  if (err) return console.log(err);  getOrders(user.id, (err, orders) => {    if (err) return console.log(err);    getPayment(orders[0], (err, pay) => {      if (err) return console.log(err);      console.log(pay.amount);    });  });});
Output
499

13.3 Creating a Promise

  • A Promise is an object that represents a result that will arrive in the future.
  • new Promise((resolve, reject) => ...): call resolve(value) on success, reject(new Error(...)) on failure.
  • Printed immediately it shows pending; then() receives the value once ready.
  • The executor function runs immediately when the Promise is created, not when then is attached.
JavaScript
function getUser(id) {  return new Promise((resolve, reject) => {    setTimeout(() => {      if (id > 0) resolve({ name: "Rahul" });      else reject(new Error("Invalid id"));    }, 500);  });} const p = getUser(1);console.log(p);p.then((user) => console.log(user.name));
Output
Promise { <pending> }Rahul
The 3 states of a Promise
  1. 1.new Promise(...) -> pending (work in progress)

  2. 2.resolve(value) -> fulfilled

  3. 3.reject(error) -> rejected

  4. 4.Fulfilled or rejected = settled

  5. 5.Settled state never changes again; then / catch callbacks run later

13.4 Promise chain: then, catch, finally

  • Each then gets the previous step's result and returns the next Promise, so the chain reads top to bottom.
  • One catch at the end handles an error from any step.
  • finally always runs, success or error (stop loaders, cleanup).
JavaScript
getUser(1)  .then((user) => getOrders(user.id))  .then((orders) => getPayment(orders[0]))  .then((pay) => console.log(pay.amount))  .catch((err) => console.log(err.message))  .finally(() => console.log("Done"));
Output
499Done
Checkpoint: getUser(0) in the same chain
  1. 1.getUser(0) -> reject(new Error("Invalid id"))

  2. 2.then(getOrders) skipped

  3. 3.then(getPayment) skipped

  4. 4.then(print amount) skipped

  5. 5.catch -> prints Invalid id

  6. 6.finally -> prints Done

Output: Invalid id, then Done

13.5 Promise.all vs allSettled vs race vs any

JavaScript
const ok = (v, t) =>  new Promise((res) => setTimeout(res, t, v));const fail = (msg, t) =>  new Promise((_, rej) =>    setTimeout(rej, t, new Error(msg))); const user = ok("user", 300);const cart = fail("cart down", 100); Promise.all([user, cart])  .then((values) => console.log(values))  .catch((err) => console.log(err.message)); Promise.allSettled([user, cart]).then((rs) =>  console.log(rs.map((r) => r.status)));
Output
cart down[ 'fulfilled', 'rejected' ]
JavaScript
const mirrorA = fail("mirror A down", 100);const mirrorB = ok("mirror B", 300); Promise.race([mirrorA, mirrorB])  .then((v) => console.log(v))  .catch((err) => console.log(err.message)); Promise.any([mirrorA, mirrorB])  .then((v) => console.log(v));
Output
mirror A downmirror B
MethodResolves whenRejects whenUse for
Promise.allAll succeed (array of values)Any one fails (immediately)Independent work that must all succeed
Promise.allSettledAll settle (array of {status, value/reason})NeverDashboards: show whatever loaded
Promise.raceFirst to settle succeedsFirst to settle failsTimeouts
Promise.anyFirst successAll fail (AggregateError)Fastest mirror / fallback servers

13.6 Common mistakes

  • Missing return inside a then with curly braces: the next then gets undefined instead of the orders.
  • No catch at the end of the chain: an unhandled rejection crashes the app in Node.
  • Rejecting with a string instead of an Error object (no stack trace, no err.message).
  • Running independent requests one after another instead of with Promise.all / allSettled.
  • Thinking then starts the work: the executor already ran at new Promise.
JavaScript
// Wrong: logs undefinedgetUser(1)  .then((user) => {    getOrders(user.id);  })  .then((orders) => console.log(orders)); // Right: logs ['A101', 'A102']getUser(1)  .then((user) => {    return getOrders(user.id);  })  .then((orders) => console.log(orders));
JavaScript
const p = new Promise((resolve) => {  console.log("Executor runs");  resolve("done");}); console.log("Promise created");p.then((v) => console.log(v));
Output
Executor runsPromise createddone

13.7 Interview tips

  • A Promise is an object representing the future result of an async task.
  • 3 states: pending, fulfilled, rejected; once settled it never changes.
  • Promises fix callback hell: flat chain, one catch, and control stays with you.
  • all rejects on the first failure, allSettled reports every status; race takes the first settled, any takes the first success.
  • The executor runs synchronously; then callbacks always run later.