Resolving Multiple Asynchronous Functions Just Once with Deferred Objects / Promises
I recently came across a piece of legacy code that had to pull data from multiple sources via AJAX requests, then combine it all. A simplified version looks like this:
var retrieveOne = function(source, cb) {
$http.get(source).success(function(data){
cb(data);
});
};
var retrieveMany = function(sources, cb) {
var dataArray = [];
var _combine = function(data){
if(data)
dataArray.push(data);
if(dataArray.length !== sources.length)
return;
//Continue combine...
cb(dataArray);
};
for(var i = 0; i < sources.length; i++){
retrieveOne(sources[i], _combine);
}
};
retrieveMany([url1, url2, ...], processData);
It works, but it’s not great. We’re calling the private function _combine multiple times, when we really should be calling it once. The biggest drawback to this that comes to mind is that...