🧠 Core Concepts

Here we will be looking into these Concepts

  • Callback basics βœ”οΈ

  • Callback vs function execution βœ”οΈ

  • Promise creation βœ”οΈ

  • Chaining βœ”οΈ

  • Return flow βœ”οΈ

  • Error handling βœ”οΈ

  • Async behavior βœ”οΈ


Function Execution vs Reference

step3();        // Executes immediately  
step3;          // Function reference (does nothing)  
() => step3();  // Function that can be executed later

πŸ‘‰ Key idea:

  • () β†’ executes now

  • function reference β†’ can be executed later

  • arrow function β†’ wrapper to delay execution

πŸ”Ή Callbacks

Basic Example

function processUser(name, callback) {  
  console.log("Processing " + name);  
  callback(name);  
}  
  
function sayHello(name) {  
  console.log("Hello " + name);  
}  
  
processUser("Mithilesh", sayHello);

Callback Hell

step1(() => {  
  step2(() => {  
    step3();  
  });  
});

❌ Problems:

  • Nested structure

  • Hard to read

  • Hard to debug

πŸ”Ή Promises

Creating a Promise

function getData() {  
  return new Promise((resolve, reject) => {  
    setTimeout(() => {  
      resolve("Data received");  
    }, 2000);  
  });  
}

Using a Promise

getData()  
  .then((data) => {  
    console.log(data);  
  })  
  .catch((err) => {  
    console.log(err);  
  });

resolve vs reject

resolve("Success"); // goes to .then()  
reject("Error");    // goes to .catch()

πŸ”Ή Promise Chaining

step1()  
  .then(() => step2())  
  .then(() => step3())  
  .catch(console.error);

Important Rule

.then() always expects a function

.then(step2)              // passes result to step2  
.then(() => step2())      // ignores result, runs step2  
.then(console.log)        // logs result

πŸ”Ή Return Flow (VERY IMPORTANT)

Correct

.then((res) => {  
  return step2(res);  
})

Wrong

.then((res) => {  
  step2(res); // ❌ no return  
})

πŸ‘‰ Result: next .then() gets undefined

Example

Promise.resolve("A")  
  .then((res) => {  
    console.log(res);  
    return "B";  
  })  
  .then((res) => {  
    console.log(res);  
  });

Output:
A  
B

Missing Return Example

Promise.resolve("A")  
  .then((res) => {  
    console.log(res);  
    "B"; // no return  
  })  
  .then((res) => {  
    console.log(res);  
  });

Output:
A  
undefined

πŸ”Ή Promise vs Value

return "B";                    // plain value  
return Promise.resolve("B");   // Promise

πŸ‘‰ Both behave the same in .then()

πŸ”Ή Nested Promise Trap

return step2(res).then((data) => {  
  console.log(data);  
});

πŸ‘‰ If no return β†’ next .then() gets undefined

Correct

return step2(res).then((data) => {  
  console.log(data);  
  return data;  
});

πŸ”Ή Error Handling

Throw inside .then()

.then(() => {  
  throw new Error("Boom");  
})  
.catch((err) => {  
  console.log(err.message);  
});

πŸ‘‰ throw = reject

Important Flow

then β†’ then β†’ throw β†’ catch

.then(success, error) vs .catch()

.then(success, error) // ❌ not recommended  
.catch(error)         // βœ… preferred

πŸ‘‰ .catch() handles:

  • rejection

  • thrown errors

  • entire chain

πŸ”Ή Recovery Pattern

Promise.reject("Error")  
  .catch((err) => {  
    console.log("Handled:", err);  
    return "Recovered";  
  })  
  .then((res) => {  
    console.log("Next:", res);  
  });

Output:

Handled: Error
Next: Recovered

πŸ”Ή When .catch() is Skipped

Promise.resolve("resolve")  
  .catch((err) => {  
    console.log(err);  
  })  
  .then((res) => {  
    console.log(res);  
  });

Output:

resolve

πŸ”Ή Transformation Chain

Promise.resolve(5)  
  .then((num) => num * 2)  
  .then((num) => num + 3)  
  .then(console.log);

Output:

13

πŸ”Ή Async Delay Example

function delay(val) {  
  return new Promise((resolve) => {  
    setTimeout(() => resolve(val), 1000);  
  });  
}  
  
delay(2)  
  .then((num) => num * 2)  
  .then((num) => delay(num + 3))  
  .then(console.log);

Output:

7

🧠 Key Mental Models

1. Promise Flow

resolve β†’ then β†’ then β†’ then  
             ↓  
           throw  
             ↓  
           catch

2. Return Flow

value β†’ return β†’ next then  
no return β†’ undefined β†’ next then

3. Function Passing

.then(fn) β†’ fn(value)

4. Promise Behavior

ActionResult
resolvethen
rejectcatch
throwreject
no returnundefined

πŸ’₯ Golden Rules

  • Always return inside .then() if chaining

  • .then() takes a function, not a value

  • throw inside Promise = rejection

  • .catch() handles everything downstream

  • Promises don’t block β€” they schedule execution