问题
I am using Angularjs $q.all(promises)
to make multiple REST call and then collecting the data once promise is successful. I have following following.
If "promises is simple array then it works Plunker
var promises = [ Users.query().$promise, Repositories.query().$promise ];
If "promises" is simple object then also it works Plunker
var promises = { users: Users.query().$promise, repos: Repositories.query().$promise };
If "promises" is nested object then it is not working. For my requirement I need nested object to remember the input parameters. Plunker
var promises = { users: {"phx":Users.query().$promise}, repos: {"phx":Repositories.query().$promise} };
These plunkr are just to simulate my problem. However I want this approach in real project for following requirement.
I have list of 12 product
Each product has "details", "benefits" and "offers" data
- I have separate REST API services for "details", "benefits" and "offers" having :productID as parameter
I am making call in following order
a. Loop for each cards
b. For each card, make a REST API call for "details", "benefits" and "offers"
c. Add #b steps into "promises" object
d. call
$q.all(promises).then(function(results) { // Here need logic to compile the result back to product // and corresponding "details", "benefits" and "offers" mapping }
and get the data back
Following is json structure I needed to collect my response.
{
"prod1": {
"benefits": {},
"offers": {},
"pages": {
"productPage": {}
}
}
},
"common": {
"benefits": {},
"pages": {
"commonBenefit": {}
},
"others": {}
}
How can I achieve this?
回答1:
If you really need it, you can wrap the nest with $q.all
like this:
var promises = {
users: $q.all({"phx": Users.query().$promise}),
repos: $q.all({"phx": Repositories.query().$promise})
};
plnkr.co
来源:https://stackoverflow.com/questions/29528087/q-allpromisesand-structure-of-promises-object-to-collect-the-returned-data