Skip to content

Instantly share code, notes, and snippets.

@kylewelsby
Created September 23, 2015 18:45
Show Gist options
  • Save kylewelsby/e678d5627d8f363a2419 to your computer and use it in GitHub Desktop.
Save kylewelsby/e678d5627d8f363a2419 to your computer and use it in GitHub Desktop.
wait until condition is met before resolving promise.
// setup
var value = false;
setTimeout(function(){
value = true;
}, 1998);
// code
function promiseWhen(condition, timeout){
if(!timeout){
timeout = 2000;
}
var done = Promise.defer();
setTimeout(function(){
done.reject();
}, timeout);
function loop(){
if(condition()){
return done.resolve();
}
setTimeout(loop,0);
}
setTimeout(loop,0);
return done.promise;
}
// test case
promiseWhen(function(){
return value === true;
}).then(function(){
console.log('done');
}, function (){
console.log('timeout');
});
@mkattner
Copy link

If the timeout triggers, your loop keeps running.

@kylewelsby
Copy link
Author

If the timeout triggers, your loop keeps running.

Good spot, there's no early return.

There's room for improvement 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment