0

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);
        });
    }
4

1 回答 1

0

我最终通过使用这样的延迟解决了这个问题:

function main(){
      var promises = [];
      return data.getItems()
                    .then(succeeded)
                    .then(function () {
                        var deferred = Q.defer();
                        Q.all(promises).done(function () {

                            logger.logError("Done");
                            return deferred.resolve(true);
                        });
                        return deferred.promise;
                    })
                   .fail(failed);
        }
    }
function succeeded(d) {
    promises = [];
    d.results.forEach(function (i) {
        promises.push([getCounts(i), getLastSubItem(i)]);
    });
}
于 2013-05-10T19:48:52.577 回答