Skip to content

Instantly share code, notes, and snippets.

@tuxracer
Last active January 4, 2016 18:09
Show Gist options
  • Save tuxracer/8659217 to your computer and use it in GitHub Desktop.
Save tuxracer/8659217 to your computer and use it in GitHub Desktop.
Resolve this promise when key on an object is truthy Public domain
# 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()
// 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