I have an array I want to iterate and, based on its length, make an async call to obtain some data I want to add to a new array.
The pseudocode looks like:
var path =["Cars", "Owners", "Name"]; var parentObject = mainObject; getChildren (path, parentObject){ var deferred = new JQuery.Deferred(); var pathSplit = path.split("."); var nestedObjectName = pathSplit[0]; var childrenIds = new Array(); if (pathSplit.length = 2){ return deferred.resolve(parentObject.Id); } else{ nestedObject = parentObject[nestedObjectName]; pathSplit.shift(); var promises = []; for (child in nestedObjects.children){ //iteration promises.push( asyncCalltoGetDetails(child).then{ //After this line, the promises array resolves. !?!?! getChildren(pathSplit, child).then(function(childId){ //recursivity childrenIds.push(childId); }); } ); } JQuery.when.apply(null, promises).then(function(){ return deferred.resolve(childrenIds); }); } return deferred.promise(); } When I make an iteration using an async call I use promises[] as explained here: How do you work with an array of jQuery Deferreds?
And when I use a recursive call using an async method I used a deferred object pass all the through way. As explained here: AngularJS, promise with recursive function
The problem I have is that promises resolve when the asyncCalltoGetDetails is made, but I want to resolve it when the recursive getChildren return the deferred.resolve();
Any idea what I'm doing wrong? How to use properly the technique of promises[] and deferred object iterated in the same method?
Thanks for your time!
var path = {"Cars", "Owners", "Name"};This is not a valid objectpromisesoutside ofgetChildren()method? Here, each time you recall getChildren(),promisesis a new array.then()chain. This is typically not difficult but requires a different mid-set.