Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Created July 25, 2024 19:57
Show Gist options
  • Save nathansmith/57e346e3f6d8960a31f71db0c7e26b95 to your computer and use it in GitHub Desktop.
Save nathansmith/57e346e3f6d8960a31f71db0c7e26b95 to your computer and use it in GitHub Desktop.
JS function that waits for dependencies, then calls them.
// Define function.
function waitForDeps(obj, list) {
// Expose promise.
return new Promise((resolve) => {
// Start polling.
const interval = setInterval(() => {
// Get missing.
const listMissing = list.filter(key => !obj[key]);
// All clear?
if (listMissing.length === 0) {
// Clear polling.
clearInterval(interval);
// Resolve promise.
resolve();
}
}, 1000);
});
}
// Example usage:
const depsObj = {};
const depsList = ['hey', 'iJustMetYou', 'thisIsCrazy', 'heresMyNumber', 'callMeMaybe'];
// Simulate delay.
setTimeout(() => {
// Loop through.
for (const key of depsList) {
// Add function.
depsObj[key] = () => console.log(key);
}
}, 1000);
// Wait for deps.
waitForDeps(depsObj, depsList).then(() => {
// Loop through.
for (const method of Object.values(depsObj)) {
// Call function.
method();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment