I want to call function named test defined in other.js, and the caller script is test.js.
// test.js
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
var other = require('./other');
async function testAsync(id){
var res = await other.test();
console.log(asyncLocalStorage.getStore());
return res;
}
async function localStorge(id_) {
var store = { id: id_ };
asyncLocalStorage.enterWith(store);
console.log("store:", asyncLocalStorage.getStore());
var res = await testAsync(id_);
}
localStorge(1);
localStorge(2);
And the callee script showed as follow.
// other.js
const {AsyncLocalStorage} = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
async function test() {
console.log(asyncLocalStorage.getStore()); // maybe it should be same as {id: x} in test.js, but get undefined
return "suc";
}
module.exports = {
test,
};
always.
In other.js, it should be {id: x} the same as test.js.
Maybe different modules could shared the same AsyncLocalStorage. And the value of the callee script depends on the caller script.
The output is always undefined.
In zone.js, different modules can share the same context using Zone.current.name.
@puzpuzpuz many thanks!!!
Maybe I should export the instance asyncLocalStorage in other.js. But I want to know if AsyncLocalStorage can be like Zone in zone.js.
Each AsyncLocalStorage doesn't share the same underlying storage. You may export the instantiated asyncLocalStorage in test.js and use this exported asyncLocalStorage in other js files.
Maybe I should export the instance
asyncLocalStoragein other.js. But I want to know ifAsyncLocalStoragecan be likeZonein zone.js.
Zone has a global static current zone property. This concept is not added to AsyncLocalStorage in purpose IIRC.
maybe you would like this #32062
Most helpful comment
Each
AsyncLocalStoragedoesn't share the same underlying storage. You may export the instantiatedasyncLocalStorageintest.jsand use this exportedasyncLocalStoragein other js files.