1
lorentz
3y

[typescript] Should I use a promise to represent an event that can occur at most once, may never occur but can never fail? If not, what else should I use? Callbacks?

Comments
  • 0
    Well actually the event occurs several times but it doesn't really make sense to listen to multiple of them so I only have a function to catch the next one.
  • 0
    I'm using rxjs observables and unsubscribing upon invocation. It's a hack, a horrible one I must say, judging by how difficult it is to unsub, but it works. I wonder what others do tho.

    Edit: I'm not a js/ts dev 😁
  • 0
    Lacking background knowledge, how do you want to represent an event as a Promise ? There is basically no difference to use a promise or callbacks. It’s just syntactic sugar IMO.
  • 0
    @dder The difference is in semantics. Promises can reject anytime for any reason. If a callback has no "error" argument you know there's nothing to handle. At the same time, promises can only be resolved once, for a callback that isn't a given. However, one might assume that a promise will resolve or reject at some point, whereas in my case that can't be known.
    Additionally, with promises I have much less control over references so it's harder to let the user cancel the request and ensure that the handler gets GCd.
  • 0
    Oh, and Promises can be passed to Promise.all([...]) as opposed to callbacks.
Add Comment