Last active
January 16, 2021 17:10
-
-
Save miketromba/38231ee6307c8f518bc94584ae6485b0 to your computer and use it in GitHub Desktop.
Get a promise which resolves once a given function returns true. The promise will set an interval and poll the function at a specified interval until it becomes true.
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
// Resolves once the check function returns true | |
// You optionally specify the interval at which to poll the check function. Default = 1000ms | |
// TODO: add timeout functionality | |
class PollingPromise extends Promise { | |
constructor(check, interval = 1000){ | |
super(resolve => { | |
if(this.check()){ return resolve() } | |
const interval = setInterval(async () => { | |
if(this.check()){ | |
clearInterval(interval) | |
return resolve() | |
} | |
}, interval) | |
}) | |
} | |
} | |
PollingPromise.prototype.constructor = Promise | |
/* Example usage: | |
class MyClass { | |
constructor(){ | |
// after you set this._isReady to true, promises returned from .ready will resolve | |
this._isReady = false | |
} | |
get ready(){ | |
return this._isReady? Promise.resolve() : new PollingPromise(() => this._isReady, 250) | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment