async-local
](https://codecov.io/gh/dimichgh/async-local)
![Known Vulnerabilities](https://snyk.io/test/github/dimichgh/async-local/badge.svg)
async_hooks based local storage aka thread-local concept in java world.
The module provides a single layer of local storage for async flow, which is more than enough for a big platform.
Install
npm install async-local -S
Usage
Express middleware example
const AsyncLocal = require('async-local');
const express = require('express');
const app = express();
app.use((req, res, next) => {
AsyncLocal.run(next);
});
Storing/reading data
const AsyncLocal = require('async-local');
console.log(AsyncLocal.get('foo'));
AsyncLocal.set('foo', 'bar');
AsyncLocal.run(ctx => {
AsyncLocal.set('foo', 'bar');
ctx.set('foo', 'bar');
const promise = Promise.resolve();;
AsyncLocal.run(ctx => {
console.log(ctx.get('foo'));
console.log(AsyncLocal.get('foo'));
AsyncLocal.set('foo', 'qaz');
console.log(ctx.get('foo'));
console.log(AsyncLocal.get('foo'));
promise.then(() => {
console.log(ctx.get('foo'));
console.log(AsyncLocal.get('foo'));
});
});
promise.then(() => {
console.log(ctx.get('foo'));
console.log(AsyncLocal.get('foo'));
});
});
Binding context
There are some edge cases when context is not preserved in async flow. For such cases, it makes sense to bind context to the function or emitter explicitly.
const EventEmitter = require('events');
const emitter = new EventEmitter();
AsyncLocal.bindEmitter(emitter);
const origFn = () => {
console.log(AsyncLocal.get('foo'));
};
AsyncLocal.run(() => {
AsyncLocal.set('foo', 'bar');
const fn = AsyncLocal.bind(origFn);
fn();
})