I am using Angular's $q to execute multiple $http post calls asynchronously. This is working nicely and the calls are all returning at roughly the same time, within a few milliseconds.
The problem is that the next step is to process the results. I want the results to be processed in parallel but they seem to be queuing up and process one at a time.
I've pasted the code below and would appreciate it if someone can point me in the right direction as to how to ensure the results are processed in parallel. This code is basically the SearchService and its 'search' method is the entry point for the controller.
var searchService = {
searchOptions: {},
searchResults: {
foos: [],
bars: [],
typeBs: [],
typeAs: []
},
searchFacets: {
foos: [],
bars: [],
typeBs: [],
typeAs: []
},
processResults: function (object, start) {
return function (response) {
//var marker = +new Date(); // log end timestamp
//var diff = marker - start;
//console.log("start processing " + object.name + ": " + diff);
...cut for brevity...
//marker = +new Date(); // log end timestamp
//diff = marker - start;
//console.log("finished processing " + object.name + ": " + diff);
}
},
getSingleSearchParams: function (object) {
return {
searchPhrase: this.searchOptions.searchPhrase,
type: object.typeId,
facets: object.facets
};
},
getSearchResults: function (object, start) {
if (object.include)
dataFactory.searchFactory.search(this.getSingleSearchParams(object)).success((this.processResults)(object, start));
else {
var message = object.name + " not selected for search";
throw message;
}
},
search: function () {
var start = +new Date();
var searches = {};
if (this.searchOptions.foos.include) {
searches.fooResults = this.getSearchResults(this.searchOptions.foos, start);
}
if (this.searchOptions.bars.include) {
searches.barResults = this.getSearchResults(this.searchOptions.bars, start);
}
if (this.searchOptions.typeBs.include) {
searches.typeBResults = this.getSearchResults(this.searchOptions.typeBs, start);
}
if (this.searchOptions.typeAs.include) {
searches.typeAResults = this.getSearchResults(this.searchOptions.typeAs, start);
}
$q.all(searches);
}
};
SearchFactory's 'search' method contains the $http calls:
searchFactory.search = function (searchOptions) {
return $http.post(searchUrl, searchOptions);
};
The commented out code shows the timings and this is revealed the serial nature of processing the results...
start processing TypeBs: 162
finished processing TypeBs: 164
start processing TypeAs: 535
finished processing TypeAs: 535
start processing Foos: 553
finished processing Foos: 554
start processing Bars: 1616
finished processing Bars: 1617