Search code examples
node.jsecmascript-2017async-hooks

What is the difference between async await and async_hooks in Node.js


async_hooks were introduced as experimental in Node v8. Because the name is similar to ES2017 async it could appear that they may be in some way related. Are they? If so, in what way (complementary or competing)?


Solution

  • async_hooks API makes it easier for you to track your resources. You start off by initializing it with an optional object of any of: init, before, after and destroy. Getting a resource triggers one of these callbacks. The point of async_hooks is to allow a better tracking of asynchronous resources and their callbacks.

    async await Lets you write code which has promise based asynchronous parts in it in a more familiar synchronous looking way.

    For example:

    async function Double() {
      let result = await PromiseWhichReturnsNumber();
    
      return result * 2;
    }
    

    In the above async function the function will pause execution at PromiseWhichReturnsNumber() until the promise is resolved (and the results are assigned to result).

    The 2 concepts are solving different issues:

    1. async await lets you write promises in a "synchronous" way.
    2. async_hooks allows you to track async resources.