google / promises

Promises is a modern framework that provides a synchronization construct for Swift and Objective-C.
Apache License 2.0
3.8k stars 293 forks source link

Question: Exposing state variables for Promise #80

Closed zackdotcomputer closed 5 years ago

zackdotcomputer commented 5 years ago

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!

shoumikhin commented 5 years ago

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:

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

Hope that helps.

zackdotcomputer commented 5 years ago

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.