util.callbackify() Method in Node.js
×


util.callbackify() Method in Node.js

210

Introduction

The util.callbackify() method in Node.js is part of the Utility Module and is used to convert an asynchronous function that returns a promise into a function that follows the traditional Node.js callback pattern.

Syntax

util.callbackify(asyncFunction)

This method takes a single argument: an async function. It returns a new function that accepts a callback as its last parameter.

Parameters

  • asyncFunction: An async function (returns a promise) that you want to convert into a callback-based function.

Return Value

Returns a new function that behaves like the original but follows the error-first callback style ((err, value)).

Important Notes

  • If the promise resolves, the callback will be called with null as the first argument and the resolved value as the second.
  • If the promise rejects, the callback will be called with the rejection reason as the first argument.
  • If the promise is rejected with a non-error value (e.g., a string), it will be wrapped in an Error object.

Example


const util = require('util');

// Async function that returns a resolved promise
async function fetchData() {
  return "Data fetched successfully";
}

// Convert to callback-style function
const callbackVersion = util.callbackify(fetchData);

// Use the function with a callback
callbackVersion((err, result) => {
  if (err) {
    console.error("Error:", err);
  } else {
    console.log("Result:", result);
  }
});
  

Output

Result: Data fetched successfully

Use Case

The util.callbackify() method is useful when working with older Node.js APIs or third-party libraries that rely on callbacks, but your code uses async/await. It acts as a bridge between modern and legacy code styles.

Conclusion

The util.callbackify() method provides a simple way to adapt modern async functions to older callback-based APIs, ensuring compatibility without rewriting logic.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat