Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Resolve a dependency recursively based on .needs
// 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
You can’t perform that action at this time.