Skip to content

Instantly share code, notes, and snippets.

@junosuarez
Created April 4, 2013 01:13
Show Gist options
  • Save junosuarez/5306900 to your computer and use it in GitHub Desktop.
Save junosuarez/5306900 to your computer and use it in GitHub Desktop.
// using Deferreds
function delay(value, timeout) {
var deferred = Q.defer()
if (typeof timeout !== 'number') {
deferred.reject(new TypeError('timeout must be a number'))
} else {
setTimeout(function () {
deferred.resolve(value)
}, timeout)
}
return deferred.promise
}
// using Promise constructor resolver
function delay2(value, timeout) {
return Q.promise(function (resolve, reject) {
if (typeof timeout !== 'number') {
reject(new TypeError('timeout must be a number'))
} else {
setTimeout(function () {
resolve(value)
}, timeout)
}
})
}
// using resolver syntax gives you the same control over resolving and rejecting promises
// without having to introduce a new concept when explaining it for the first time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment