Node: asyncLocalStorage shared in different modules

Created on 31 Mar 2020  路  4Comments  路  Source: nodejs/node

  • Version:v13.12.0
  • Platform: linux
  • Subsystem:

What steps will reproduce the bug?

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,
};

How often does it reproduce? Is there a required condition?

always.

What is the expected behavior?

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.

What do you see instead?

The output is always undefined.

Additional information

In zone.js, different modules can share the same context using Zone.current.name.

@puzpuzpuz many thanks!!!

Most helpful comment

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.

All 4 comments

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 asyncLocalStorage in other.js. But I want to know if AsyncLocalStorage can be like Zone in 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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stevenvachon picture stevenvachon  路  3Comments

sandeepks1 picture sandeepks1  路  3Comments

vsemozhetbyt picture vsemozhetbyt  路  3Comments

akdor1154 picture akdor1154  路  3Comments

cong88 picture cong88  路  3Comments