Async programming in JavaScript for dummies

Gulshan Nadaph
2 min readNov 28, 2024

--

Callbacks

Scenario: You want your cat to fetch a toy, but you need to give it instructions step-by-step.

function fetchToy(callback) {
console.log("Cat is fetching the toy...");
setTimeout(() => {
callback("Toy fetched! 🧸");
}, 1000);
}

fetchToy((message) => {
console.log(message); // Output after 1 second: Toy fetched! 🧸
});

When to use: Use callbacks when you have simple, sequential tasks and don’t mind the “callback hell” (nested callbacks).

Promises

Scenario: You promise your cat a treat if it fetches the toy, and the cat decides whether to fulfill the promise.

function fetchToy() {
return new Promise((resolve, reject) => {
console.log("Cat is fetching the toy...");
setTimeout(() => {
const success = Math.random() > 0.5; // 50% chance of success
if (success) {
resolve("Toy fetched! 🧸");
} else {
reject("Cat got distracted! 🐱");
}
}, 1000);
});
}

fetchToy()
.then((message) => {
console.log(message); // Output: Toy fetched! 🧸
})
.catch((error) => {
console.error(error); // Output: Cat got distracted! 🐱
});

When to use: Use promises when you need better error handling and chaining of asynchronous tasks.

Async/Await

Scenario: You ask your cat to fetch the toy and wait patiently for it to return, handling success or failure gracefully.

function fetchToy() {
return new Promise((resolve, reject) => {
console.log("Cat is fetching the toy...");
setTimeout(() => {
const success = Math.random() > 0.5; // 50% chance of success
if (success) {
resolve("Toy fetched! 🧸");
} else {
reject("Cat got distracted! 🐱");
}
}, 1000);
});
}

async function getToy() {
try {
const message = await fetchToy();
console.log(message); // Output: Toy fetched! 🧸
} catch (error) {
console.error(error); // Output: Cat got distracted! 🐱
}
}

getToy();

When to use: Use async/await for cleaner, more readable code when dealing with multiple asynchronous operations.

In summary:

  • Callbacks: Simple tasks, but can get messy with nested callbacks.
  • Promises: Better error handling and chaining.
  • Async/Await: Clean and readable code for complex asynchronous operations.

--

--

No responses yet