Promise-returning delay function

Tab Atkins Jr. jackalmage at
Mon Oct 27 07:52:49 PDT 2014

On Mon, Oct 27, 2014 at 3:21 AM, Andrea Giammarchi
<andrea.giammarchi at> wrote:
> Not sure if discussed already but I believe `.cancel()` or
> `.forgetAboutIt()` mechanism should be proposed before introducing any
> `.delay()`
> Promises often put developers in unmanaged roads where things keep being
> "forgotten" and/or impossible to drop without ending up in the next chain,
> undesired, or the error stack, even less desired.
> What I mean is that if `setTimeout` is a desired pattern to replicate
> through `.delay(ms)`, but I really don't understand why that would be a
> desired pattern at all, `clearTimeout` functionality should be considered as
> well.
> A generic `.cancel()` would be most likely the easier approach but it should
> be implemented upfront.

Cancelable promises are a completely different beast; it's not just a
matter of adding a new method to Promise.prototype, it's changing the
data structure pretty fundamentally.  Suddenly you have a new
value-affecting capability, but it's exposed outside of the
constructor.  You need to be able to react to a cancellation, so you
can actually cancel the work being done, and possibly resolve the
promise to some default value (or error).

A promise that auto-resolves after a timeout, on the other hand, is a
straightforward utility function of obvious usefulness, and requires
no additional work:

Promise.delay = function(ms) {
  return new Promise(function(r) { setTimeout(r, ms); });

(Not tested, but this should be approximately right.)


More information about the es-discuss mailing list