Created
May 20, 2014 23:10
-
-
Save benjamingr/0ed038727f38fb77e7ee to your computer and use it in GitHub Desktop.
Resolve a dependency recursively based on .needs
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
// this will load a script, I assume each dependency contains what it needs inside | |
// `dependency.needs` and we'll load that. | |
// | |
// stuff is called script here, but it could also be a stylesheet or whatever. | |
// | |
// Since when we return a promise from a `.then` it unwraps and runs the promise we return, we can | |
// return a promise for the values of our _own_ dependencies, and continue doing so, promises will | |
// unwrap everything for us. | |
// | |
// This does not do have the same `.addDependency` interface from before, it's just a function to show | |
// a concept, but if it | |
// Assume a magical scriptFromName function exists that takes a script name returns the document's script element for it. | |
function resolve(script){ | |
var needs = script.needs; // what we need | |
var needsDependencies = needs.map(function(need){ // we take each need | |
var dependencyData = scriptFromName(need); // this function gets the dependency | |
return resolve(dependencyData); // so, we're resolving the dependencies for it too | |
}); | |
rerturn Promise.all(needsDependencies) // when all my dependencies resolved their own dependencies | |
.then(function(dependentScripts){ // all the scripts have also run here, we'll see how soon | |
script.execute(); // execute this script, since all the dependent scripts were | |
// themselves resolved, we can safely assume our dependencies are met now | |
}); // we also return a promise here, so we can hook on when it's done, | |
//note we used this in our resolve call above | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment