Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
async
asyncify

How to use Asyncify in JavaScript's Async Module

Educative Answers Team

Asyncify

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.

svg viewer

Usage

The following example demonstrates how the asyncify() function can be used:

import asyncify from 'async/asyncify.js';

// Synchronously defined function
function synchronousFunction(){
  return "Function ended";
}

// Defining callback function
function callback(data, val) {
	// Second argument contains returned value
  	console.log(val);
}

async function main(){
  
  
  // Converting function to asynchronous
  var asyncFunction = asyncify(synchronousFunction);

  // Calling function
  asyncFunction(callback);
  
}

// Calling main
main()

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.

RELATED TAGS

javascript
async
asyncify
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring