The util.callbackify() method is an inbuilt application programming interface of the util module which is used to run an asynchronous function and get a callback in the node.js.
Syntax:
util.callbackify( async_function )
Parameters: This method accepts single parameter as mentioned above and described below.
- async_function: It is required parameter, signifies an original async function.
Return Value: It returns a promise as an error-first callback style function. which takes (err, ret) => {} as parameter, first argument of which is error or rejection reason, possibly null(when promise is resolved), and the second argument is the resolved value.
Below examples illustrate the use of util.callbackify() method in Node.js:
Example 1:
javascript
const util = require( 'util' );
async function async_function() {
return 'message from async function' ;
}
const callback_function =
util.callbackify(async_function);
callback_function((err, ret) => {
if (err) throw err;
console.log(ret);
});
|
Output:
message from async function
Example 2:
javascript
const util = require( 'util' );
async function async_function() {
return Promise.reject( new Error(
'this is an error message!' ));
}
const callback_function =
util.callbackify(async_function);
callback_function((err, ret) => {
if (err && err.hasOwnProperty( 'reason' )
&& err.reason === null ) {
console.log(err.reason);
} else {
console.log(err);
}
});
|
Output:
Error: this is an error message!
at async_function (C:\nodejs\g\util\callbackify_2.js:6:25)
at async_function (util.js:356:13)
at Object. (C:\nodejs\g\util\callbackify_2.js:12:1)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
Note: The above program will compile and run by using the node filename.js command.
Reference: https://nodejs.org/api/util.html#util_util_callbackify_original
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Oct, 2021
Like Article
Save Article