Created
July 25, 2024 19:57
-
-
Save nathansmith/57e346e3f6d8960a31f71db0c7e26b95 to your computer and use it in GitHub Desktop.
JS function that waits for dependencies, then calls them.
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
// 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