Skip to content

AsyncLocalStorage loses a context #2537

Description

@Doc999tor
  • Node.js Version: 13.11
  • OS: Win10
  • Scope (install, code, runtime, meta, other?): Code
  • Module (and version) (if relevant): async_hooks

Docs say: In this example, the store is only available in the callback function and the functions called by foo. Outside of runSyncAndReturn, calling getStore will return undefined.
I need the store available in the scope of asyncRouter only
How should I persist context is the example below?
Thanks

Express plain example:
File: async-store.js

const { AsyncLocalStorage } = require("async_hooks");
exports.asyncLocalStorage = new AsyncLocalStorage();

File: app.js

const { asyncLocalStorage } = require("./async-store");
const { asyncRouter } = require("./async-router");
const app = express();
asyncLocalStorage.runSyncAndReturn({}, async () => {
    console.log(asyncLocalStorage.getStore()); // Prints `{}` - as expected
    app.use(asyncRouter); // neither a regular
    // await Promise.resolve(app.use(asyncRouter)); # neither promised call keeps the context
});

File async-router.js

const { asyncLocalStorage } = require("./async-store");
exports.asyncRouter = router;
router.get('/async-test', async (req, res) => {
    console.log(asyncLocalStorage.getStore()); // _undefined_
    res.send();
});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions