NodeJS Promises vs aSync

1. Promises

A Promise is an object representing a value that will be available in the future (resolved or rejected).
It’s the foundation of async handling in modern JS.

Example:

function getData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve("✅ Data ready"), 1000);
  });
}

getData().then(data => console.log(data)) // handle success
         .catch(err => console.error(err)); // handle error

👉 You attach .then() for success, .catch() for errors.
👉 Chaining works, but deeply nested .then() can get messy.


🔹 2. async/await

async/await is syntax sugar on top of Promises.
It makes asynchronous code look like synchronous code.

  • async → marks a function that returns a Promise.
  • await → pauses execution until the Promise settles.

Example:

async function showData() {
  try {
    const data = await getData(); // waits for promise
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

showData();

👉 Same logic as the previous Promise example, but cleaner and easier to read.


🔹 Key Differences

FeaturePromise (.then)async/await
SyntaxChained .then() and .catch()Looks synchronous with await
Error handling.catch()try/catch
ReadabilityCan get messy in chainsCleaner, more sequential
Return valueAlways a PromiseAlways a Promise
Under the hoodCore featureJust syntactic sugar over Promises

🔹 Example side by side

Promise version

fetchData()
  .then(res => processData(res))
  .then(result => saveData(result))
  .catch(err => console.error(err));

async/await version

async function main() {
  try {
    const res = await fetchData();
    const result = await processData(res);
    await saveData(result);
  } catch (err) {
    console.error(err);
  }
}
main();

Both do the same thing ✅


🔹 Exam traps

  1. async function always returns a Promise: async function foo() { return 42; } foo().then(console.log); // logs 42
  2. await can only be used inside an async function (except in ES2022+ where top-level await is supported in modules).
  3. Mixing await inside loops: for (let i of arr) { await doSomething(i); // runs sequentially ❌ (slow) } Better: await Promise.all(arr.map(doSomething)); // runs in parallel ✅

Summary:

  • Promise → lower-level, flexible, but chaining can reduce readability.
  • async/await → built on Promises, makes async code much easier to read and write.

Leave a Reply

Your email address will not be published. Required fields are marked *