google / promises

Promises is a modern framework that provides a synchronization construct for Swift and Objective-C.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: Exposing state variables for Promise

zackdotcomputer opened this issue · comments

Sorry for leaving this as an Issue when it's more a "Request for change"

I notice that there are three protected accessors on Promises called isPending, isFulfilled, and isRejected. I've run into a case where it would be very useful to be able to introspect the isPending value in a synchronous way, but can't. Is there a reason for these variables to be protected, rather than being read-only public?

For the record, my use case is that I have a cache access function that returns a Promise, meaning that it's likely that it has either already been fulfilled or it will take quite some time to fulfill. I would like to be able to introspect that value synchronously so that I can show a loading spinner before attaching the handler via the .then chain. The app currently just always shows the loading spinner, but it is an unpleasant experience to flash it very quickly and it strikes me that there would be no issue with exposing this value.

Please let me know if there's something I'm missing here, thanks!

Hi Zack,

The functions you've mentioned are designed for testing purposes only. Exposing promise's state and checking it explicitly is usually error prone, because it potentially leads to race conditions.

Imagine your cache access function had a completion handler instead. How would you solve your issue with the activity indicator UX then? There's couple of ways on the top of my mind:

  • provide another sync function that would return either nil or a value directly if it's present in cache; if you got nil, then call the async function
  • add an out argument of boolean type along with completion handler to tell if there was a cache miss
  • delay showing the activity indicator and skip that if completion handler fired earlier

Similarly, you can use one of those patterns when you have an async func that returns a promise.

Hope that helps.

Thank you for the thoughtful reply, @shoumikhin! I had also landed on the solution of providing a direct access method and using the Promise as a fallback and it's working just fine. Thanks again and have a good week.