maybe your JS function (being loaded from a different host) does not have access to the mage-cache-storage key in localStorage due to partitioned browser storage? That might be the case in Brave for example(?)
It might improve the situation when you ask for the value before it’s available. Of course, here I assume that you’ll use it at later stage (one of the following datalayer events).