-
Notifications
You must be signed in to change notification settings - Fork 395
when delay
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()
:
var delay = require('when/delay');
function doSomething() { ... }
// These are equivalent
setTimeout(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.
var delay = require('when/delay');
var value = 'hi';
// Using setTimeout requires wrapping
setTimeout(function() {
console.log(value);
}, 1000);
// Using delay to forward the value
delay(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.
var delay = require('when/delay');
function doAsyncCalculation() {
// ...
return promise;
}
// This will log the result of doAsyncCalculation *1 second after*
// it completes.
delay(doAsyncCalculation(), 1000).then(console.log);