node/test/async-hooks/test-async-local-storage-enter-with.js
Stephen Belanger d368dcc63a async_hooks: add sync enterWith to ALS
This allows transitioning the entire following sync and async execution
sub-tree to the given async storage context. With this one can be sure
the context binding will remain for any following sync activity and all
descending async execution whereas the `run*(...)` methods must wrap
everything that is intended to exist within the context. This is helpful
for scenarios such as prepending a `'connection'` event to an http
server which binds everything that occurs within each request to
the given context. This is helpful for APMs to minimize the need
for patching and especially adding closures.

PR-URL: https://github.com/nodejs/node/pull/31945
Reviewed-By: Vladimir de Turckheim <vlad2t@hotmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Michael Dawson <michael_dawson@ca.ibm.com>
2020-03-09 14:24:21 -04:00

21 lines
515 B
JavaScript

'use strict';
require('../common');
const assert = require('assert');
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
setImmediate(() => {
const store = { foo: 'bar' };
asyncLocalStorage.enterWith(store);
assert.strictEqual(asyncLocalStorage.getStore(), store);
setTimeout(() => {
assert.strictEqual(asyncLocalStorage.getStore(), store);
}, 10);
});
setTimeout(() => {
assert.strictEqual(asyncLocalStorage.getStore(), undefined);
}, 10);