a blog for those who code

Friday, 14 July 2017

What is Async Hooks in Node.js 8

In this post we will be discussing about Async Hooks in Node.js 8. Async Hooks API will allow the developers to track asynchronous requests and handles through their complete life-cycle. In our previous post we have discussed What is New in Node.js Version 8, in that Async Hooks is one of the noticeable feature added in the new version of Node.js. Now we will further discuss about Async Hooks and what will be its advantage.

According to Node.js Doc, Async Hooks module provides an API to register callbacks tracking the lifetime of asynchronous resources (i.e. an object with an associated callback) created inside a Node.js application. It can be accessed inside the application using the below code :

const async_hooks = require('async_hooks');

The advantage of using Async Hooks API is that the API emits events which has all the information about the life of all handle objects. This is important because then you know about all the objects and what all the changes its going through in its life time.

To start with we have to create a AsyncHook instance and then allow the callbacks to be called as shown below ;

const asyncHook = aync_hooks.createHook(callbacks)
// the callbacks to register and returns AsyncHook instance used for enabling and disabling hooks
// the callbacks used are init(), before(), after() and destroy() and these are all optional.
asyncHook.enable()
// it enables the callbacks for a given AsyncHook instance
asyncHook.disable()
// it disables the callbacks for a given AsyncHook instance

Still its a very early age for Async Hooks and its done on an experiment basis but its a very important feature for developers because now all the asynchronous requests can be tracked by the users.

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a comment