Created
April 18, 2018 11:41
-
-
Save nire0510/28847dbe66ac44827c64f59b5e0527ed to your computer and use it in GitHub Desktop.
Wait until condition is truthy and only then - proceed
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
/** | |
* Example of an async function which returns some value | |
*/ | |
function doSomething() { | |
return new Promise((resolve, reject) => { | |
window.setTimeout(function () { | |
resolve(Math.random() > 0.8); | |
}, 1000); | |
}); | |
} | |
/** | |
* Checks whether a condition applies, in order to tell waitUntil to proceed | |
* @param {object} data - The response from the business function above | |
*/ | |
function evaluate(data) { | |
return data === true; | |
} | |
/** | |
* Waits for a condition to be truthy and proceed | |
*/ | |
async function waitUntil(extract, evaluate, max) { | |
let data; | |
let truthy; | |
let counter = 0; | |
while ((!max||counter < max) && !truthy) { | |
data = await extract(); | |
truthy = evaluate(data); | |
counter++ | |
}; | |
return data; | |
} | |
// how to use: | |
waitUntil(doSomething, evaluate) | |
.then(isTrue => console.log(isTrue)); | |
// how to use - try 3 times maximum: | |
waitUntil(doSomething, evaluate, 3) | |
.then(isTrue => console.log(isTrue)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment