How can I synchronously determine a JavaScript Promise's state? (Domenic Denicola)

# Ron Waldon (9 years ago)

Apologies if this is a duplicate: I'm new to mailing lists and got a little bit muddled.

legacy use case

I am maintaining an existing API that includes asynchronous functions (mix of callbacks and Promises) and synchronous functions. After some asynchronous initialisation, the internal state settles and it is perfectly safe to use the synchronous functions as expected.

So, I'd like to emit warnings when these synchronous functions are called prior to a Promise being "settled". That way, downstream developers will know that they should be waiting for the Promise to settle before using such functions.

This actually isn't too different to the XHR / Fetch APIs conceptually. We get the ball rolling with an asynchronous API call, but there are deterministic blocks within which we can synchronously interrogate progress, etc.

activity indicator use case

I use a Promise to represent a network transaction. I wish to alter the visual state of my web app to reflect the state of this network transaction. I can, for example, show an indeterminate progress bar whilst the Promise is not "settled".

If I am using requestAnimationFrame, or a framework like React, then the state would be synchronously mapped to the DOM / canvas during each execution of my render function.

I can track the state of the Promise using additional variables (as others have suggested), but those state values already exist somewhere private per the functioning of a Promise. I'd be duplicating work that the JavaScript engine is already performing internally, at the risk of introducing errors in my code.

third-party popular libraries

The following libraries implement some form of Promise and all expose such synchronous inspection capabilities: