How can I synchronously determine a JavaScript Promise's state?

Ron Waldon jokeyrhyme at gmail.com
Tue Jun 2 00:55:23 UTC 2015


## 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:

- jQuery: http://api.jquery.com/deferred.state/
- Bluebird:
https://github.com/petkaantonov/bluebird/blob/master/API.md#synchronous-inspection
- Q:
https://github.com/kriskowal/q/wiki/API-Reference#state-inspection-methods
- Lie: https://github.com/calvinmetcalf/lie/blob/master/lib/promise.js#L17


On Tue, 2 Jun 2015 at 07:31 Domenic Denicola <d at domenic.me> wrote:

> I will repeat to you what I said on Specifiction:
>
> > To get a standard API for this, you'll need to convince the JavaScript
> standard committee, as well as the browser vendors, that your use case is
> widespread and important enough to be worth the standardization and
> implementation burden, and that it cannot be achieved in any other possible
> way.
> >
> > So ... go!
>
> Looking forward to your use cases, preferably with examples showing code
> in popular libraries or apps that would benefit to illustrate how
> wide-spread those use cases are.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150602/2ab67bd3/attachment-0001.html>


More information about the es-discuss mailing list