/**
* takes a list of componentIDs to load, relative to componentRoot
* returns a promise to the map of (ComponentID -> componentCfg)
*/
function asyncLoadComponents (componentRoot, components) {
var componentCfgs = {};
function asyncLoadComponentCfg(component) {
var url = _.sprintf("%s/%s", componentRoot, component);
var promise = util.getJSON(url);
promise.done(function(data) {
componentCfgs[component] = data;
});
return promise;
}
var promises = _.map(components, asyncLoadComponentCfg);
var flattenedPromise = $.when.apply(null, promises);
var componentCfgPromise = flattenedPromise.pipe(function() {
// componentCfgs is loaded now
return $.Deferred().resolve(componentCfgs).promise();
});
return componentCfgPromise;
}
var locale = 'en-US';
var componentRoot = '/api/components';
var components = ['facets', 'header', 'DocumentList'];
function buildDocumentListPage(locale, componentCfgs) { /* code goes here */ }
$.when(asyncLoadComponents(componentRoot, components)).done(function(componentCfgs) {
buildDocumentListPage(locale, componentCfgs)
});
Take the 2-minute tour
×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
|
|||
|
i have fully generalized thanks to Joseph's help. So this could parallelize and sequence by key arbitrary async things, like say a database query to load objects by ID. library code:
application code:
can we do even better, or is this it? |
|||||
|
Here's a sample in jsFiddle, with some values and functions mocked-up to use jsFiddle API. Here's the actual code, with notes in the comments:
Packed code looks like this, tons shorter:
|
|||||
|