Node.js util.callbackify() Method
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
// Node.js program to demonstrate the // util.callbackify() Method // Allocating util module const util = require( 'util' ); // Async function to be called // from util.callbackify() method async function async_function() { return 'message from async function' ; } // Calling callbackify() const callback_function = util.callbackify(async_function); // Listener for callback_function callback_function((err, ret) => { if (err) throw err; console.log(ret); }); |
Output:
message from async function
Example 2:
javascript
// Node.js program to demonstrate the // util.callbackify() Method // Allocating util module const util = require( 'util' ); // Async function to be called // from util.callbackify() method async function async_function() { return Promise.reject( new Error( 'this is an error message!' )); } // Calling callbackify() const callback_function = util.callbackify(async_function); // Listener for callback_function callback_function((err, ret) => { // If error occurs if (err && err.hasOwnProperty( 'reason' ) && err.reason === null ) { // Printing error reason 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
Please Login to comment...