I'm trying to get the following scheme to work: I have a an ajax call that returns an array of objects (promise). Now, I have a succeeded function that does additional handling on each item in the array, including making other async ajax calls. Of course, this creates a headache because the main succeeded() function returns before the sub-functions are done, which is not what I want. Each sub-function call also returns a promise, and I want to leave the main function only when all items load.
Here's what I've tried so far. The main function getItemData is not waiting for the Q.all(...) to return. I'm using the JS Async and the Q.js libraries:
function main() {
//performs an ajax get to grab items from server
return data.getItems().then(succeeded).fail(failed);
}
function succeeded(d) {
async.each(d.results, getItemData, function (err) { logger.logError(err) });
function getItemData(item, callback) {
//counts
item.totalSubItems = ko.observable(0);
Q.all([getCounts, getLastSubItem]).then(function fulfilled() {
items.push(item);
return callback;
});
};
function getCounts() {
//another ajax call that returns a promise
data.getItemCounts(item.id()).then(function (c) {
var results = c.results;
//some work
})
.fail(function (error) {
logger.logError(error);
});
function getLastSubItem() {
//also returns a promise
data.getLastSubItem(item.id()).then(function (sub) {
item.lastsub(sub.results[0]);
})
.fail(function (error) {
logger.logError(error);
});
}