Created
July 30, 2015 22:48
-
-
Save joeheyming/1ecc65586c189e7c3bad to your computer and use it in GitHub Desktop.
treewalk example
This file contains hidden or 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
/** | |
* @param {object[]} dependencies A list of steps to do at each depth of the tree. | |
* dependencies[0] is invoked first, then we call dependencies[1] on each child action. etc. | |
* @param {function} dependencies.request A function that returns a promise. | |
* @param {function:object[]} dependencies.onSuccess A function to call after the promise from dependencies.request finishes. | |
* This function should return a list of objects to invoke the next depth dependency on. | |
* | |
* @param {function} onFinish What to do when everything node has been traversed. | |
*/ | |
DataLoader.walkTree = function(dependencies, onFinish) { | |
var innerWalk; | |
var counter = 0; | |
var finalData = {}; | |
function checkCounter() { | |
if (counter === 0) { | |
if(_.isFunction(onFinish)) { | |
onFinish(finalData); | |
} | |
} | |
}; | |
innerWalk = function(dependencies, optData, optIndex) { | |
var depth = optIndex || 0; | |
var dependency = dependencies[depth]; | |
if (_.isUndefined(dependency)) { | |
// handle null recursive case | |
checkCounter(); | |
return; | |
} | |
var promise = dependency.request(optData); | |
counter = counter + 1; | |
promise.then(function onWalkSuccess(response) { | |
counter = counter - 1; | |
var success = dependency.onSuccess(response.obj, optData); | |
success = _.isArray(success) ? success : [success]; | |
_.each(success, function(data) { | |
innerWalk(dependencies, data, depth + 1); | |
}); | |
}).fail(function onWalkFail(response) { | |
counter = counter - 1; | |
checkCounter(); | |
}); | |
}; | |
innerWalk(dependencies, finalData); | |
}; | |
//// Example of it in action: | |
DataLoader.walkTree([{ | |
request: function(data) { | |
return Deployment.list({environment: environment.name()}); | |
}, | |
onSuccess: function(deploymentNames, parent) { | |
parent.deployments = _.map(deploymentNames, function(depName) { | |
return { | |
name: depName, | |
environment: environment.name(), | |
clusters: [] | |
}; | |
}); | |
return parent.deployments; | |
} | |
}, { | |
request: function(parent) { | |
return Cluster.list({environment: environment.name(), deployment: parent.name}); | |
}, | |
onSuccess: function(clusterNames, deployment) { | |
_.each(clusterNames, function(clusterName) { | |
var cluster = { | |
environment: environment.name(), | |
deployment: deployment.name, | |
name: clusterName | |
}; | |
deployment.clusters.push(cluster); | |
}); | |
} | |
}], function done(data) { | |
window.console.log('data = ', data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment