Reputation: 152
I am using AsyncLocalStorage to keep track of events running in my backend (userId, url etc.). A store is made for each separate event running using the same AsyncLocalStorage:
//At startup one AsyncLocalStorage context is made
const context = new AsyncLocalStorage()
And then when an event starts (for example an API call) I use context.run
const runWithStore = (data: any, callBack: () => any) => {
return context.run(data, () => {
callBack();
});
};
Now I am wondering how this store gets garbage collected? Is it after callBack
has finished?
Reason for asking: I am running into a really weird issue where a "post save" hook (mongoose) is using a store that has nothing to do with this hook (hook is running because of an internal event).
Logically the store should be unavailable because the "post save" hook is outside of the main flow. But the behaviour seems quite random. Sometimes the store is unavailable (as it should be) But at times it is using a store created for a WS event that has long been dealt with (and had nothing to do with this "post save" hook)
So I am wondering what is going on underneath, since these stores should definitely not be shared between different events.
Upvotes: 2
Views: 342
Reputation: 1874
The data you store within the context (asyncLocalStorage.getStore()) is independent of the AsyncLocalStorage instance itself. This data gets garbage collected along with the corresponding asynchronous operation when it finishes. There's no separate call needed to manage the garbage collection of the stored data.
Upvotes: 0