I am creating a middleware for adding trace id to each req and come across async hook and async localstorage, but I am confused about why next function is passed inside the run method, and when I remove the next function and move it outside the run function the middleware does not work as expected so can someone please explain to me what does putting next() inside run() is doing to make things work. Below is the code sample-
app.use((req, res, next) => {
asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set("requestId", uuid());
next();
});
});
If you place
next()outside the callback, it will not be run within the context created byasyncLocalStorageand (hence) you won't be able to access the store.This is also explained in the documentation: