Created
February 7, 2019 10:50
-
-
Save jayantbh/7ec64bb70c67ee803b0d32439cd41121 to your computer and use it in GitHub Desktop.
JS - Wait for given function to return true before proceeding
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
import { waitFor } from './waitFor'; | |
let unrelatedStuffValue = false; | |
async function test() { | |
const result = await waitFor(() => unrelatedStuffValue); | |
console.log('Result: ', result); // Result: true | |
} | |
async function unrelatedAsyncStuff() { | |
await fetch('.'); // any async action | |
unrelatedStuffValue = true; | |
} | |
unrelatedAsyncStuff(); | |
test(); |
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
export const waitFor = (func = () => {}) => { | |
const RETRY_DELAY = 100; | |
return new Promise(resolve => { | |
const retrialFunction = () => { | |
if (!func()) return setTimeout(retrialFunction, RETRY_DELAY); | |
resolve(func()); | |
}; | |
retrialFunction(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment