Variables scoped by a chain of asynchrounous calls
const Variable = require('continuation-local-variable');
const User = Variable.create('user');
User.set("Moe");
setTimeout(function() {
print(Variable.find('user').value()); // prints 'Moe'
}, 1000);
// User name will be 'Larry' for the chain of async operations
// starting with `setTimeout`
User.set("Larry");
setTimeout(function() {
print(Variable.find('user').value()); // prints 'Larry'
// http request
axios.get('http://www.github.com').then(() => {
print(Variable.find('user').value()); // still prints 'Larry'
})
}, 700);
// User name is 'Curly' for the async chain starting with the next `setTimeout`
User.set("Curly");
setTimeout(function() {
print(Variable.find('user').value()); // prints 'Curly'
process.nextTick(() => {
print(Variable.find('user').value()); // prints 'Curly'
});
}, 500);
NodeJS 8.9 or above
Creates a new async scoped variable
Finds an existing variable
Sets the value of the variable. This value will hold for the duration of the next asynchronous call chain.
Returns the value of this variable.