asyncify()
takes a synchronous function and makes it asynchronous. Synchronous functions are functions in which each operation occurs one after the other whereas, asynchronous functions execute in parallel with other functions. Their results can be accessed when ready using promises, callbacks, or special keywords like await.
The following example demonstrates how the asyncify()
function can be used:
import asyncify from 'async/asyncify.js';// Synchronously defined functionfunction synchronousFunction(){return "Function ended";}// Defining callback functionfunction callback(data, val) {// Second argument contains returned valueconsole.log(val);}async function main(){// Converting function to asynchronousvar asyncFunction = asyncify(synchronousFunction);// Calling functionasyncFunction(callback);}// Calling mainmain()
This example defines a synchronousFunction()
. The function is converted to an asynchronous function (asyncFunction()
) on line 18 and is run on line 21.
It is important to note that this method requires a callback function to send the resultant value to. This callback function is defined on line 9 and is passed as an argument in the converted async function. The resultant return value is stored in the second parameter of the callback.
Free Resources