In programming β especially JavaScript β you often deal with asynchronous processing.

In programming β especially JavaScript β you often deal with asynchronous processing. Itβs vital because:
In JavaScript:
Example: Synchronous
1console.log("Start");
2console.log("Processing...");
3console.log("End");
4Result:
1Start
2Processing...
3EndExample: Asynchronous (setTimeout)
1console.log("Start");
2
3setTimeout(() => {
4 console.log("Processing after 2 seconds");
5}, 2000);
6
7console.log("End");Result:
1Start
2End
3Processing after 2 secondsπ§ Remember:
JS is single-threaded, but uses an event loop to manage async behavior.
A callback is a function passed into another function, called after some operation finishes.
Example 1: Callback after delay
1function doTask(callback) {
2 setTimeout(() => {
3 console.log("Task done!");
4 callback();
5 }, 1000);
6}
7
8doTask(() => {
9 console.log("Callback invoked after task.");
10});β Easy to understand, but can lead to Callback Hell if deeply nested!
Example 2: Callback Hell
1function makeBurger(callback) {
2 setTimeout(() => {
3 console.log("Making the bun");
4 callback();
5 }, 1000);
6}
7
8function addLettuce(callback) {
9 setTimeout(() => {
10 console.log("Adding lettuce");
11 callback();
12 }, 500);
13}
14
15function addSauce(callback) {
16 setTimeout(() => {
17 console.log("Adding sauce");
18 callback();
19 }, 300);
20}
21
22makeBurger(() => {
23 addLettuce(() => {
24 addSauce(() => {
25 console.log("Burger ready!");
26 });
27 });
28});
29β Problem: Difficult to read, maintain, and debug!
Promises help manage asynchronous code more cleanly, avoiding deeply nested callbacks.
Example 3: Basic Promise
1function cookRice() {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => {
4 const isSuccess = true;
5 if (isSuccess) resolve("Rice cooked!");
6 else reject("Rice burned...");
7 }, 2000);
8 });
9}
10
11cookRice()
12 .then((result) => console.log(result))
13 .catch((error) => console.error(error));
14Example 4: Promise chaining
1function step1() {
2 return new Promise((resolve) => {
3 setTimeout(() => {
4 console.log("Step 1");
5 resolve();
6 }, 1000);
7 });
8}
9
10function step2() {
11 return new Promise((resolve) => {
12 setTimeout(() => {
13 console.log("Step 2");
14 resolve();
15 }, 500);
16 });
17}
18
19step1()
20 .then(() => step2())
21 .then(() => {
22 console.log("Finished!");
23 });
24Async/Await (introduced in ES2017) allows you to write Promise-based code in a synchronous style, making it extremely readable.
Example 5: Basic Async Await
1function boilingWater() {
2 return new Promise((resolve) => {
3 setTimeout(() => {
4 resolve("Water is boiling!");
5 }, 1500);
6 });
7}
8
9async function makeTea() {
10 console.log("Boiling water...");
11 const result = await boilingWater();
12 console.log(result);
13 console.log("Making tea...");
14}
15
16makeTea();Example 6: Error handling with try/catch
1function getWeather() {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => {
4 const success = false;
5 if (success) resolve("Sunny!");
6 else reject("Rainstorm...");
7 }, 1000);
8 });
9}
10
11async function showWeather() {
12 try {
13 const forecast = await getWeather();
14 console.log("Forecast:", forecast);
15 } catch (error) {
16 console.error("Error:", error);
17 }
18}
19
20showWeather();
21β
try/catch makes error handling very clean.
Example 7: Sequential execution
1async function sequential() {
2 const res1 = await fetch('https://jsonplaceholder.typicode.com/posts/1');
3 const res2 = await fetch('https://jsonplaceholder.typicode.com/posts/2');
4 console.log("Sequential done:", res1.status, res2.status);
5}
6
7sequential();
8Example 8: Parallel execution using Promise.all
1async function parallel() {
2 const [res1, res2] = await Promise.all([
3 fetch('https://jsonplaceholder.typicode.com/posts/1'),
4 fetch('https://jsonplaceholder.typicode.com/posts/2'),
5 ]);
6 console.log("Parallel done:", res1.status, res2.status);
7}
8
9parallel();
10β
Promise.all saves time by executing tasks concurrently.
Promise.race: Returns the first settled promise (whether resolved or rejected).Promise.allSettled: Waits for all promises to settle (regardless of success or failure).Example 9: Promise.race
1async function fastestOne() {
2 const result = await Promise.race([
3 fetch('https://jsonplaceholder.typicode.com/posts/1'),
4 fetch('https://jsonplaceholder.typicode.com/posts/2')
5 ]);
6 console.log("Fastest response:", result.url);
7}
8
9fastestOne();
10Example 10: Promise.allSettled
1async function checkAll() {
2 const results = await Promise.allSettled([
3 Promise.resolve("Success"),
4 Promise.reject("Failure"),
5 ]);
6 console.log(results);
7}
8
9checkAll();Result:
1[
2 { status: "fulfilled", value: "Success" },
3 { status: "rejected", reason: "Failure" }
4]