I have a function that iterates through an undetermined number of items and performs asynchronous calls on each to retrieve additional data (specifically, the content of HTML template files). The callback also includes some validation checks. The end result should be chainable. $q is injected beforehand, and this code is a part of a factory.
function searchHelpTopics(topics, searchPhrase) {
if (topics == null || topics.length == 0) return "No search results";
var results = [];
var promises = [];
for (var i = 0; i < topics.length; i++) {
var templateURL = topics[i].URL;
var topic = topics[i];
if (topics[i].HelpTopicId != "Search") {
var promise = $templateRequest(templateURL).then(function (template) {
var text = HTMLToText(template, true);
// perform the search
if (text.indexOf(searchPhrase) > -1) {
if (text.length > 50) text = text.substring(0, 50);
var result = {};
result.title = topic.Title;
result.excerpt = text;
result.helpID = topic.HelpTopicID;
results.push(result);
}
});
promises.push(promise);
}
}
return $q.all(promises).then(function () {
return results;
})
The issue here is that the for loop does not wait for the callbacks to finish, causing the callback to operate on the incorrect topic object. I need a method to pass the correct topic into the callback during each iteration.