Last active
January 4, 2016 18:09
-
-
Save tuxracer/8659217 to your computer and use it in GitHub Desktop.
Resolve this promise when key on an object is truthy Public domain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Resolve this promise when key on an object is truthy | |
# Optionally you can pass a timeout when to give up and how frequently to check | |
# Returns a promise resolved or rejected with the value given | |
whenTruthy = (key, obj = mediator, timeout = 60000, frequency = 100) -> | |
dfd = new $.Deferred | |
if obj[key] | |
dfd.resolve obj[key] | |
else | |
giveUp = setTimeout -> | |
clearInterval checking | |
dfd.reject obj[key] | |
, timeout | |
checking = setInterval -> | |
if obj[key] | |
clearInterval giveUp | |
clearInterval checking | |
dfd.resolve obj[key] | |
, frequency | |
dfd.promise() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Converted from CoffeeScript | |
var whenTruthy = function(key, obj, timeout, frequency) { | |
var checking, dfd, giveUp; | |
if (obj == null) { | |
obj = mediator; | |
} | |
if (timeout == null) { | |
timeout = 60000; | |
} | |
if (frequency == null) { | |
frequency = 100; | |
} | |
dfd = new $.Deferred; | |
if (obj[key]) { | |
dfd.resolve(obj[key]); | |
} else { | |
giveUp = setTimeout(function() { | |
clearInterval(checking); | |
return dfd.reject(obj[key]); | |
}, timeout); | |
checking = setInterval(function() { | |
if (obj[key]) { | |
clearInterval(giveUp); | |
clearInterval(checking); | |
return dfd.resolve(obj[key]); | |
} | |
}, frequency); | |
} | |
return dfd.promise(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment