0

Ok I'm new to JavaScript programming and I'm really struggling with the async stuff. I have tried to show my example below:

Controller

$scope.handleClick = function(stuff) {
    var promise = fetchOtherStuffs(stuff.id1);
    var promiseTwo = fetchOtherStuffs(stuff.id2);

    $q.all([promise, promiseTwo]).then(function(data) {
        // fails because data is undefined
        console.log(data[0].length);
        console.log(data[1].length);
    }); 
 };

var fetchOtherStuffs = function(stuffId) {
    return $http.get('http://localhost/myapi/stuff/' + stuffId)
        .then(function(theStuffs) {
            var promises = [];

            for (var i = 0; i < theStuffs.data.length; i++) {
                var otherStuffId = theStuffs.data[i].otherStuffId;
                promises.push( 
                $http.get('http://localhost:8085/myapi/otherstuff/' 
                     + otherStuffId));
            }

            $q.all(promises).then(function(data){
                var result = [];

                for (var i = 0; i < promises.length; i++) {
                    result.push(data[i].data[i]);
                }

                // this works and the data count is as expected
                console.log('returning: ' + result.length);            
                return result;
        });               
  });           
};

So I need to:

  • call myapi/stuff
  • take the result of that call (which can be many Objects) and call the /myapi/otherstuff for each of those Objects
  • return all of those Objects from otherstuff back to the handleClick method

I really don't know how to implement the fetchOtherStuffs method so the promise is returns actually returns a value when it's needed in the handleClick method.

Thanks a lot.

Alex
  • 7,639
  • 3
  • 45
  • 58
planetjones
  • 12,469
  • 5
  • 50
  • 51

1 Answers1

2

You forgot a small little return in the then callback after getting myapi/stuff:

function fetchOtherStuffs(stuffId) {
    return $http.get('http://localhost/myapi/stuff/' + stuffId)
    .then(function(theStuffs) {
         …
         return $q.all(promises).then(function(data){
//       ^^^^^^
             …
             return result;
         });
    });
}

Also, I'm not sure whether accessing an [i] property twice in

for (var i = 0; i < promises.length; i++) {
    result.push(data[i].data[i]);
}

is correct, but that of course depends on the format of the data.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • +1 ... The other downvote seems like it was retaliatory. – Ben Lesh Sep 09 '14 at 15:45
  • thanks a lot - i will go home tonight with a print out of some promise blogposts so i understand a little better. and now i've changed the code i only need data[i] too, as you suggest. – planetjones Sep 09 '14 at 15:49
  • If you only use `.push(data[i])` (and not `data[i].data.…` or so) you can omit that whole `.then()` callback (if you don't care about the logging), as `data == result` :-) – Bergi Sep 09 '14 at 15:52