Facebook Pixel

Converting Callbacks to Promises in JavaScript

Promisify converts callback-based APIs to promises. Here is how to do it manually and with util.promisify.

Converting Callbacks to Promises in JavaScript

Many older APIs (Node.js fs, crypto) are callback-based. You can convert them to promises with promisify or manually.

Manual Promisification

function promisify(fn) { return (...args) => { return new Promise((resolve, reject) => { fn(...args, (err, result) => { if (err) reject(err); else resolve(result); }); }); }; } const readFileP = promisify(fs.readFile); readFileP("file.txt", "utf8") .then((data) => console.log(data)) .catch((err) => console.error(err)); `` `promisify` takes a callback-based function and returns a promise-based one. The callback must follow the error-first convention (`(err, result) => {}`). ### Using `util.promisify` (Node.js) Node.js provides `util.promisify`: ```js const { promisify } = require("util"); const fs = require("fs"); const readFileP = promisify(fs.readFile); readFileP("file.txt", "utf8") .then((data) => console.log(data)) .catch((err) => console.error(err)); `` Or with async/await: ```js async function main() { try { const data = await readFileP("file.txt", "utf8"); console.log(data); } catch (err) { console.error(err); } } `` ### Node.js Promise-Based APIs Many Node.js APIs now have promise-based versions built in: ```js const fs = require("fs").promises; // or const fs = require("fs/promises"); async function main() { const data = await fs.readFile("file.txt", "utf8"); console.log(data); } `` No need to promisify. Use `fs/promises` directly. ### Promisifying Event-Based APIs Some APIs are event-based, not callback-based. Promisifying them is different: ```js function once(emitter, event) { return new Promise((resolve, reject) => { emitter.once(event, resolve); emitter.once("error", reject); }); } const server = net.createServer(); await once(server, "listen"); `` Node.js provides `events.once` for this: ```js const { once } = require("events"); await once(server, "listen"); `` ### The Takeaway Convert callbacks to promises with `promisify` (manual) or `util.promisify` (Node.js). Many Node.js APIs now have promise-based versions (`fs/promises`). Promisifying event-based APIs uses `new Promise` with `once` or `events.once`. Use async/await with the promisified versions for clean code.

Wrap it in a new Promise. Call the original function with a callback that calls reject on error and resolve on success. Return the promise. The callback must follow the error-first convention: (err, result) => {}.

A built-in utility that converts a callback-based function (error-first convention) to a promise-based one. Usage: const readFileP = promisify(fs.readFile). Then use it with .then or async/await.

Yes. Many APIs have promise-based versions. Use require('fs').promises or require('fs/promises') for file system, for example. No need to promisify manually. Use them with async/await.

Use new Promise with emitter.once: new Promise((resolve, reject) => { emitter.once(event, resolve); emitter.once('error', reject); }). Node.js provides events.once(emitter, event) for this.

The callback's first argument is an error (null if no error). The second argument is the result. promisify checks if (err) reject(err) else resolve(result). The original function must follow this convention.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.