$q.all(promises)and structure of promises object to collect the returned data

Deadly 提交于 2019-12-25 14:11:12

问题


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.

  1. If "promises is simple array then it works Plunker

    var promises = [
       Users.query().$promise,
       Repositories.query().$promise
    ];
    
  2. If "promises" is simple object then also it works Plunker

    var promises = {
       users: Users.query().$promise,
       repos: Repositories.query().$promise
    };
    
  3. 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.

  1. I have list of 12 product

  2. Each product has "details", "benefits" and "offers" data

  3. I have separate REST API services for "details", "benefits" and "offers" having :productID as parameter
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!