Skip to content

Instantly share code, notes, and snippets.

@vdeturckheim
Created May 1, 2020 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vdeturckheim/6af191b3633a2c856315a2473d282566 to your computer and use it in GitHub Desktop.
Save vdeturckheim/6af191b3633a2c856315a2473d282566 to your computer and use it in GitHub Desktop.

AsyncLocalStorage API

The AsyncLocalStorage class has been introduced in the Async Hooks module.

This API allows keeping a context across asynchronous operations. For instance, if an sequence id is stored within an instance of AsyncLocalStorage for each entering HTTP requests in a server, it will be possible to retrieve this id without knowing the current HTTP request.

const http = require('http');
const { AsyncLocalStorage } = require('async_hooks');

const asyncLocalStorage = new AsyncLocalStorage();

function logWithId(msg) {
  const id = asyncLocalStorage.getStore();
  console.log(`${id !== undefined ? id : '-'}:`, msg);
}

let idSeq = 0;
http.createServer((req, res) => {
  asyncLocalStorage.run(idSeq++, () => {
    logWithId('start');
    // Imagine any chain of async operations here
    setImmediate(() => {
      logWithId('finish');
      res.end();
    });
  });
}).listen(8080);

In this example, the logWithId function, will always know what the current request id is.

What can this API be used for

Use cases of this API include:

  • logging
  • User identification
  • Performance tracking
  • Error trancking and handling
  • much more!

Note: This API is still experimental and some methods might change in the next releases of Node.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment