promise - jQuery async calls on array -


i'm trying following scheme work: have ajax call returns array of objects (promise). now, have succeeded function additional handling on each item in array, including making other async ajax calls. of course, creates headache because main succeeded() function returns before sub-functions done, not want. each sub-function call returns promise, , want leave main function when items load.

here's i've tried far. main function getitemdata not waiting q.all(...) return. i'm using js async , q.js libraries:

function main() {     //performs ajax grab items 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 returns promise         data.getitemcounts(item.id()).then(function (c) {             var results = c.results;             //some work         })          .fail(function (error) {             logger.logerror(error);        }); function getlastsubitem() {         //also returns promise         data.getlastsubitem(item.id()).then(function (sub) {             item.lastsub(sub.results[0]);         })         .fail(function (error) {             logger.logerror(error);         });     } 

i ended solving issue using deferreds this:

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

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -