Search code examples
angularjsapiangular-promiseangular-resource

Return multiple data independent resource promises


Via this link I've found an example of returning multiple resource promises (lines 44-52):

http://embed.plnkr.co/LZad4ZyEYjrbKiTPbAwu/script.js

var GistsData = Gists.query();
var MetaData = Meta.get();

GistsData.$promise.then(function(response) {console.log('Resource 1 data loaded!')});
MetaData.$promise.then(function(response) {console.log('Resource 2 data loaded!')});

return $q.all([GistsData.$promise, MetaData.$promise]);

In my case the second resource API call (MetaData) is dependent on a specific value that is returned by the first resource API call (GistsData).

I try to figure out how I can use a value that is returned by GistData (for example an ID) in the MetaData resource? Like this:

var MetaData = Meta.get({ id : GistsData.id });

I want to return a promise after the MetaData with the ID has returned a promise.

Thank you


Solution

  • Firstly I suggest you do a little more reading about promises, as they are awesome :)

    As for your question, what you want to do is promise chaining. Notice how you are utilising the .then() functions for each of the resource promises. then() gets called once the promise has resolved, which in your case is when the queries have returned.

    So instead of running each one independently, use the then() function of the first promise to then begin running the second. For example:

    return Gists.query().$promise.then(function(response){
        // Gists has finished and the data it returned is in response
        // Now run your second query, using the response from the first
    
        return Meta.get({ id : response.id }).$promise.then(function(nextResponse){
    
            // Now nextResponse will contain the result of Meta.get(), having used the id that returned from the first response
            console.log(nextResponse);
        });
    });
    

    Now there are nicer ways to write the above, but hopefully it explains chaining enough for you.