Skip to content

Instantly share code, notes, and snippets.

@jayantbh
Created February 7, 2019 10:50
Show Gist options
  • Save jayantbh/7ec64bb70c67ee803b0d32439cd41121 to your computer and use it in GitHub Desktop.
Save jayantbh/7ec64bb70c67ee803b0d32439cd41121 to your computer and use it in GitHub Desktop.
JS - Wait for given function to return true before proceeding
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();
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