简体   繁体   English

我应该如何在AngularJS中处理两个异步调用?

[英]How should I handle two asynchronous calls in AngularJS?

I have a controller which loads different attributes of my data via two separate http calls. 我有一个控制器,它通过两个单独的http调用加载数据的不同属性。 An overly simplified example would be something like: 过于简化的示例如下所示:

  • A Country class which has attributes name, official language, and population 具有名称,官方语言和人口属性的Country类
  • one service (A) which returns countries and their languages 一种返回国家及其语言的服务(A)
  • another service (B) which returns countries and their populations 另一种返回国家及其人口的服务(B)
  • let's assume that the set of countries returned in B is a subset of the countries returned in A, and I don't know either set ahead of time 假设B中返回的国家/地区集是A中返回的国家/地区的子集,而我不知道这两个国家/地区提前
  • I want to end up with an array of Country objects - all countries returned by A, with their populations set (based on the data returned by B) 我想最后得到一个Country对象数组-A返回的所有国家及其种群(基于B返回的数据)

If the calls were synchronous, I would simply do something like: 如果调用是同步的,则只需执行以下操作:

- call service A and store Objects in a map keyed by Country name
- call service B, iterate over results:  if a result in is the previous map, then update its population field

But of course I can't do that because the call to service B might return first, so the map is empty. 但是我当然不能这样做,因为对服务B的调用可能首先返回,因此映射为空。

I have tried using promises via the "$broadcast"/"$on" functionality, but this doesn't work consistently because both calls are asynchronous (I broadcast when B is done, and try to apply the results to A, but sometimes A has not finished yet). 我曾尝试通过“ $ broadcast” /“ $ on”功能使用promise,但是由于两个调用都是异步的,因此无法始终如一地工作(我在B完成后进行广播,并尝试将结果应用于A,但有时A尚未完成)。

What should I do here? 我该怎么办?

只是看连锁应许

Promises allow developers to easily attach 1x-only notifications of response to any asynchronous request/action. 承诺使开发人员可以轻松地将响应的仅1x通知附加到任何异步请求/操作。 Promises also enable two (2) other very important things. 承诺还使其他两(2)个非常重要的事情成为可能。 We can: 我们可以:

Transform the responses before subsequent handlers (in the chain) are notified of the response. 在通知后续处理程序(在链中)之前,转换响应。 Use the response to invoke more async requests (which could generate more promises). 使用响应来调用更多异步请求(这可能会产生更多的承诺)。 But even more important than the features above, Promises support easy chaining of custom activity or computations. 但是,比以上功能更重要的是,Promises支持轻松链接自定义活动或计算。 Managing sequences or chains of asynchronous activity can be a very difficult and complex effort. 管理异步活动的序列或链可能是非常困难和复杂的工作。 Promise chains are amazing and provide means to easily build sequences of asynchronous requests or asynchronous activity. 承诺链令人惊奇,并提供了轻松构建异步请求或异步活动序列的方法。

Refer - Flattening Promise Chains 参考-展平承诺链

    var app = angular.module("app",[]);


    app.factory('myService', function($http,$q) {
        return {
            getPerson: function(){

            return $q.all([
                $http.jsonp('http://filltext.com/?callback=JSON_CALLBACK&rows=10&delay=2&fname={firstName}&lname={lastName}'),
                $http.jsonp('http://filltext.com/?callback=JSON_CALLBACK&rows=10&delay=2&fname={firstName}&city={city}')
                ]).then(
                function(result) { return result },  /* SUCCESS */
                function() { return "NaN" } /* FAILURE */
                );
            }
        };
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM