When we execute some async code in javascript. The async callback function will lost the execution context of the main thread. We always using closure like below to make it possible for async callback to access the variable in main thread.
function foo() {
let localVariable = 5;
setTimeout(function callback() {
console.log(localVariable); // -> this is accessed through closure
}, 100);
}
foo();
// 5
However, if the code is in separate modules. how could we make the context in main thread to be accessed by async call back.
// a.js file
let callback = require("./b.js");
function foo() {
let someContext = {
/* some data */
};
setTimeout(callback, 100);
}
// b.js file
function callback() {
let someContext; // -> how can we get `someContext` in the execution context of foo
console.log(someContext);
}
the context continuation is based on async hooks, which is first introduced into nodeJS version 8.
// a.js file
require("../src/index");
// a.js file
let callback = require("./b.js");
function foo() {
setTimeout(callback, 100);
}
let c = _currentActive.current.fork({ properties: { a: 5 } });
c.runInContext(foo);
// b.js file
function callback() {
let data = _currentActive.current.get("a");
console.log(data); // -> print out 5
}
module.exports = callback;
setTimeout
setImmediate
setInterval
process.nextTick
native promise