Skip to content

Return a default value for a promise that times out

Brian Cavalier edited this page Jul 21, 2014 · 2 revisions

It can be very useful to use promise.timeout(millis) to ensure that promise consumers don't wait an unreasonable amount of time for a task. Sometimes, though, instead of rejecting the returned promise, it can be useful for the producer to return some default value when the promise times out.

Using promise.timeout together with promise.else (or its ES3 alias, promise.orElse) makes this easy.

For example, if the real value can't be computed/fetched in 5 seconds, return a default instead:

return promiseForComputedValue
  .timeout(5000)
  .else(defaultValue);
Clone this wiki locally