Skip to content
tatablack edited this page Mar 29, 2013 · 3 revisions

The when/delay helper creates a promise that automatically resolves after a specified delay, if not rejected sooner. In its simplest form, when/delay can behave like a promise-based version of setTimeout():

vardelay=require('when/delay');functiondoSomething(){ ... }// These are equivalentsetTimeout(doSomething,1000);delay(1000).then(doSomething);

But, when/delay has a few other tricks up its sleeve. It can accept two arguments, the first of which may be a promise or a value, allowing it to forward that on to the handler.

vardelay=require('when/delay');varvalue='hi';// Using setTimeout requires wrappingsetTimeout(function(){console.log(value);},1000);// Using delay to forward the valuedelay(value,1000).then(console.log);

When passing a promise as the first argument, the delay will happen after that input promise resolves, and will forward the resolution value of the promise.

vardelay=require('when/delay');functiondoAsyncCalculation(){// ...returnpromise;}// This will log the result of doAsyncCalculation *1 second after*// it completes.delay(doAsyncCalculation(),1000).then(console.log);

Clone this wiki locally