- 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();
});
Docs say: In this example, the store is only available in the callback function and the functions called by
foo. Outside ofrunSyncAndReturn, callinggetStorewill returnundefined.I need the store available in the scope of
asyncRouteronlyHow should I persist context is the example below?
Thanks
Expressplain example:File: async-store.js
File: app.js
File async-router.js