Skip to main content

Episode 4: Async / Await


πŸ”Ή Introduction​

async β€” A keyword in JavaScript used to create asynchronous functions.
Async functions always return a Promise, regardless of what you return inside them.


🧩 Example 1: Async Function Always Returns a Promise​

async function getData() {
return "Namaste JS";
}

const dataPromise = getData();
console.log(dataPromise);

dataPromise.then((res) => console.log(res));

πŸ“˜ Output:

Promise {<fulfilled>: "Namaste JS"}
Namaste JS

βœ… Even though we're returning a string, JavaScript automatically wraps it in a Promise.


πŸ”Ή Handling Promises Using Async / Await​

const p = new Promise((resolve, reject) => {
resolve("Promise Resolved Value!");
});

async function handlePromise() {
const val = await p;
console.log(val);
}

handlePromise();

πŸ’‘ await pauses the execution of the async function until the promise resolves.


πŸ” Deep Dive: Promise Resolution vs Async / Await​

🧩 Normal .then() Approach​

const p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise resolved value!");
}, 10000);
});

function getData() {
p.then((res) => console.log(res));
console.log("Namaste JS");
}

getData();

πŸ“˜ Output:

Namaste JS
// after 10 seconds
Promise resolved value!
async function getData() {
return "Namaste JS";
}

const dataPromise = getData();
console.log(dataPromise);

dataPromise.then((res) => console.log(res));

πŸ“˜ Output:

Promise {<fulfilled>: "Namaste JS"}
Namaste JS

βœ… Even though we’re returning a string, JavaScript automatically wraps it in a Promise.


πŸ”Ή Handling Promises Using Async / Await​

const p = new Promise((resolve, reject) => {
resolve("Promise Resolved Value!");
});

async function handlePromise() {
console.log("Hello World");

const val = await p;
console.log("Namaste JavaScript");
console.log(val);

const val2 = await p;
console.log("Namaste JavaScript 2");
console.log(val2);
}

handlePromise();

πŸ“˜ Output:

Hello World
// after 10 seconds
Namaste JavaScript
Promise resolved value!
Namaste JavaScript 2
Promise resolved value!

⚑ Key Insight:
β€œTime, tide, and JavaScript wait for none.”
JavaScript doesn’t literally pause execution. When it sees an await, it suspends the function execution and lets the event loop handle other tasks until the awaited Promise resolves.


πŸ”Ή Example with Multiple Promises​

const p1 = new Promise((resolve) => {
setTimeout(() => resolve("Promise 1 Resolved!"), 1000);
});

const p2 = new Promise((resolve) => {
setTimeout(() => resolve("Promise 2 Resolved!"), 5000);
});

async function handlePromise() {
console.log("Hello World");

const v1 = await p1;
console.log("Namaste JavaScript");
console.log(v1);

const v2 = await p2;
console.log("Namaste JS 2");
console.log(v2);
}

handlePromise();

πŸ“˜ Output:

Hello World
// after 1 second
Namaste JavaScript
Promise 1 Resolved!
// after 5 seconds
Namaste JS 2
Promise 2 Resolved!

🌐 Real-World Example: Fetching API Data​

const API_URL = "https://api.github.com/users/prakhaaar";

async function handlePromise() {
try {
const data = await fetch(API_URL);
const jsonValue = await data.json();
console.log(jsonValue);
} catch (err) {
console.log("Error:", err);
}
}

handlePromise().catch((err) => console.log(err));

πŸ“˜ Notes:

  • fetch() returns a Promise.
  • response.json() also returns a Promise.
  • Hence we use two awaits.
  • We can handle errors via try...catch or .catch().

πŸ’¬ Interview Insights: Async / Await​

1️⃣ async keyword is used to create asynchronous functions.
2️⃣ await can only be used inside an async function.
3️⃣ It’s used to wait for promises to resolve in a cleaner, synchronous-like manner.
4️⃣ Helps avoid callback hell or long promise chains.
5️⃣ Under the hood, it’s just syntactic sugar over .then() and .catch().


βš–οΈ Async / Await vs .then() / .catch()​

FeatureAsync / AwaitPromise .then()
SyntaxSynchronous-lookingChained callbacks
ReadabilityVery clean and readableBecomes messy with many chains
Error Handlingtry...catch.catch()
Under the HoodBuilt on PromisesBase Promise handling

πŸ’‘ Async/Await is preferred for modern codebases β€” cleaner flow, easier debugging, and fewer nested callbacks.


🧾 Recap​

βœ… async β†’ always returns a Promise
βœ… await β†’ pauses async function until Promise resolves
βœ… JS doesn’t block, it suspends function execution
βœ… Handle errors with try...catch
βœ… Perfect for sequential async operations


Watch Live On YouTube below:

Namaste JS Video Thumbnail