Promises & async/await
Promises & Async await
1. What is a Promise?
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value.
Think of it like a food pager at a restaurant:
Pending: You are waiting for the food.
Fulfilled (Resolved): The food is ready, and you get your meal.
Rejected: The kitchen ran out of ingredients, and you get an error message.
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Data received!");
} else {
reject("Error: Request failed.");
}
});
myPromise
.then((data) => console.log(data)) // Handles success
.catch((err) => console.log(err)); // Handles failure2. Async / Await
Introduced in ES2017, async and await are "syntactic sugar" built on top of Promises. They make the code much cleaner by removing the need for .then() and .catch() chains.
async: A keyword placed before a function to make it return a promise.await: A keyword used inside an async function to pause execution until a promise is resolved.
function fetchData() {
fetch('https://api.example.com/items')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
}
async function fetchData() {
try {
const res = await fetch('https://api.example.com/items');
const data = await res.json();
console.log(data);
} catch (err) {
// try/catch replaces .catch()
console.error("Custom Error Message:", err);
}
}3. Converting Callbacks to Promises (Promisify)
Since many older Node.js modules (like fs) still use error-first callbacks, Node provides a utility called util.promisify to convert them into Promises.
const fs = require('fs');
const util = require('util');
// Convert the callback-based readFile into a promise-based one
const readFilePromise = util.promisify(fs.readFile);
async function getFileContent() {
try {
const data = await readFilePromise('data.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}4. Why use Async/Await over Callbacks?
Readability The code reads from top to bottom, making it easier for other developers to follow the logic.
Error Handling
You can use standard try/catch blocks, which handle both synchronous and asynchronous errors in the same place.
Debugging
Setting breakpoints is much easier with await because the code pauses on that specific line. In a callback chain, debugging can become confusing as the execution "jumps" around.
Avoiding the Pyramid of Doom Instead of nesting functions inside functions, you keep your code at a flat indentation level.