machty / ember-concurrency

ember-concurrency is an Ember Addon that enables you to write concise, worry-free, cancelable, restartable, asynchronous tasks.
http://ember-concurrency.com
MIT License
690 stars 157 forks source link

Adjust return value of `timeout()` #330

Open Turbo87 opened 4 years ago

Turbo87 commented 4 years ago

I'm trying to use timeout() to implement an actual timeout using race(), but I would like to adjust the value that is returned from timeout(), so that I can distinguish between that case, and the other promise returning undefined.

timeout(42).then(() => 'foo') sort of works, but since the returned promise no longer has the __ec_cancel__() method it is not cancelable anymore.

I would like to propose adding an optional second argument to timeout() (and rawTimeout()) that will adjust the return value of the returned promise: timeout(42, 'foo')

maxfierke commented 4 years ago

once #331 is merged, a then()'d timeout will be cancelable. (edit: then() always ends up as a regular promise :/ )

This is an interesting idea, though. I could see this also being useful for when you want to simulate some sort of delay before returning a value (e.g. simulated network calls) or a default value if a something else times out (in the context of use with race(), for example)

let user = yield race([
  slowApi.getUser(),
  yield timeout(1000, { 
    data: {
      id: -1,
      type: 'user'
      attributes: {
        first_name: "Default",
        last_name: "Person"
      }
    }
  })
]);