JavaScript Promisification

JavaScript Promisification

JavaScript Promisification

Promisification is the process of converting a function that uses callbacks into a function that returns a Promise. This makes it easier to work with async/await and chaining.

🔹 1. Why Promisify?

Traditional callback-based functions can be difficult to manage, especially with callback hell. Promisification makes them cleaner and easier to use.

🛑 Callback-based function (Bad way)

function fetchData(callback) { setTimeout(() => { callback(null, "📦 Data received!"); }, 1000); } fetchData((err, data) => { if (err) { console.error("❌ Error:", err); } else { console.log("✅ Success:", data); } });

Problem: Hard to manage, especially with nested calls.

🔹 2. Converting to a Promise-based Function

We wrap the function inside a Promise. Instead of using callback(error, result), we use resolve(result) for success and reject(error) for failure.

Promisified function

function fetchDataPromise() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("📦 Data received!"); }, 1000); }); } fetchDataPromise() .then((data) => console.log("✅ Success:", data)) .catch((error) => console.log("❌ Error:", error));

🚀 Benefits:
✔ No more callback hell
✔ Works with .then() and async/await

🔹 3. Using Promisification with async/await

Now that we have a promise-based function, we can use async/await for even cleaner code.

async function getData() { try { let data = await fetchDataPromise(); console.log("✅ Success:", data); } catch (error) { console.log("❌ Error:", error); } } getData();

🚀 Even cleaner and easier to read!

🔹 4. Promisifying a Callback Function

If a function follows the common Node.js callback pattern (callback(err, result)), we can automate the promisification.

🔹 Example: Node.js fs.readFile

const fs = require("fs"); const { promisify } = require("util"); const readFilePromise = promisify(fs.readFile); readFilePromise("example.txt", "utf8") .then((data) => console.log("📄 File Content:", data)) .catch((error) => console.error("❌ Error:", error));

promisify() converts the function automatically!

🔹 5. Manual Promisification of Any Callback Function

function delay(ms, callback) { setTimeout(() => { callback(null, `Waited ${ms}ms`); }, ms); } // 🔹 Promisify the function function delayPromise(ms) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(`Waited ${ms}ms`); }, ms); }); } // 🔹 Using Promise delayPromise(2000).then(console.log);

No callback needed!

🔹 6. Handling Errors in Promisification

If the callback has an error (callback(err, result)), we reject the promise.

function fetchData(callback) { setTimeout(() => { let success = Math.random() > 0.5; if (success) callback(null, "📦 Data received!"); else callback("❌ Network Error", null); }, 1000); } // 🔹 Promisify function function fetchDataPromise() { return new Promise((resolve, reject) => { fetchData((err, data) => { if (err) reject(err); else resolve(data); }); }); } // 🔹 Using the Promisified Function fetchDataPromise() .then(console.log) .catch(console.error);

✔ Handles both success and failure gracefully!

🔹 Summary

MethodCallbacksPromisified
Traditional Callbackcallback(err, result).then(result).catch(err)
Nested HellHard to manageFlat, clean structure
Async/Await❌ Not possible✅ Works perfectly

Promisification makes callback-based functions easier, cleaner, and modern!

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close