async-cls
dead simple "continuation-local storage" with Node async_hooks
Install
npm install async-cls
Usage
continuation local storage allows you to implicitly make values available to an asynchronous chain of code.
Multiple asynchronous chains of the same code can be running simultaneously, and each will only get access to its own value.
var cls = require('async-cls')
var express = require('express')
var userContext = cls()
var app = express()
app.get('/', function (req, res) {
userContext.current = req.user
setTimeout(function () {
respond(res)
})
})
function respond (res) {
res.json({ userId: userContext.current.id })
}
API
context = cls()
Create a new context. A context can hold a single JavaScript value per async context.
context.current = value
Set the value for this async context (call stack).
context.current
Get the value for this async context.
context.destroy()
Destroy the context, removing its async_hook
and cleaning up any context values. Accessing context.current
after the context has been destroyed will return undefined
.
License
Apache-2.0