Created
September 23, 2015 18:45
-
-
Save kylewelsby/e678d5627d8f363a2419 to your computer and use it in GitHub Desktop.
wait until condition is met before resolving promise.
This file contains 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
// 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'); | |
}); |
You saved my life. Thank you :)
Your welcome @SimonBrandner
If the timeout triggers, your loop keeps running.
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
You saved my life. Thank you :)