Pete's Log: Awaiting Promises

Entry #1895, (Coding, Hacking, & CS stuff)
(posted when I was 42 years old.)

My particular use case for doing what I describe below is React Single Page Applications, but I'm sure it applies more generally.

I've been using a design pattern these past few years for background-loading data my web app will eventually need. In pseudo-code it looks something like this. At page load:

const dataINeedLater = LoadTheDataINeedLater();

Where LoadTheDataINeedLater loads the data asynchronously and resolves it via a Promise.

Later, any time I want to use that data, I just await that Promise.

const theData = await dataINeedLater; const foo = theData.bar;

It's worked quite well for me. Awaiting a promise multiple times seems to just work. If I happen to await it before the load function finishes, then I pause until it's done. If I await it after it's already done, I continue immediately. My google-fu never helped me find any arguments either in favor or against this approach, but since it worked, I've kept using it.

Raymond Chen, whose blog I've been enjoying for about 16 or 17 years now, is in the middle of a series on how to make C++/WinRT events that can be awaited more than once. Apparently unlike JavaScript Promises, C++/WinRT usually only allows one completion callback for an asynchronous operation.

He states that "one use case for an awaitable signal is having every call to a function first wait for some one-time initialization to complete."

One commenter on that series of posts adds "In JavaScript you can of course await the same Promise multiple times, and it’s really handy to be able to create something asynchronously, so to speak, and then have all the users await the result of the creation."

So it felt real nice to passively find some validation for this approach that I've occasionally wondered about.