3

Im using a REST Api that provides non-nested resources API. That leads to chained calls, that i want to make with promises. Im using the ngResource from angular, and im having problem chaining the calls. The idea is first to get the description of an active element. Here i ask for an JSON, response looks like this :

{id : 0, block : [0,3,4]} 

After i got this information, i try to get the data about blocks. The implementation looks like this:

Element.get({'id':state.elementID}).$promise.then( function(element) {
            // Element hast block entry with array of belonging blockIDs
            angular.forEach(element.block, function(blockId){
                // Get all the Blocks, that have the defined ID ( Foreign key)
                return Block.get({'id':blockId}).$promise;
            });
        }).then(function(block){
            // Create an element and ADD it to the model
            var uiElem = new UIElem(block.id, "#",block.name, "block");
            $scope.list.push(uiElem);
            angular.forEach(block.parameter, function(element){
                /// Chain other calls...
                .......

            });
        })

The problem that the second then gets undefined block, although the GET call get a correct JSON from the server.

Im wondering if i am using the chaining of the promises incorrectly or im using the elements wrong

Sonne
  • 691
  • 1
  • 6
  • 20

2 Answers2

1

You are not correctly chaining your promises. For each block you sending another request to the server immediatly.

Use $q.all for chaining:

    // Element hast block entry with array of belonging blockIDs
    return $q.all(element.block.map(function(blockId){
        // Get all the Blocks, that have the defined ID ( Foreign key)
        return Block.get({'id':blockId}).$promise;
    }));

This should give you the array of resulting blocks here: }).then(function(blocks){...

Andre Kreienbring
  • 2,457
  • 11
  • 16
  • Thanks, that is a good answer. One question remains for me: Since in the following chain of calls, the ids of e.g. Block are needed. How can i pass those to the other "then" functions? To extend prototype is a bogus for me, is there any better solution? – Sonne Oct 19 '15 at 12:29
  • As you get an array (of blocks) in the following 'then', you should be able to access for example blocks[0].id. And please accept my answer if it is correct to help other who may have the same question. – Andre Kreienbring Oct 19 '15 at 12:34
  • Firefox is complaining that element.block is undefined. Why? – Sonne Oct 26 '15 at 17:37
0

The chained promises use the previous promise's result as an input. You have no return in your first promise, thus the second receiving undefined as its block.

You should return element or whatever is relevant in your first promise.

This is described in the $q documentation.

Aaron
  • 24,009
  • 2
  • 33
  • 57