【问题标题】:Multiple asynchronous calls to the same API function with different parameters in AngularJS在AngularJS中对具有不同参数的同一个API函数进行多次异步调用
【发布时间】:2020-01-22 21:08:12
【问题描述】:

考虑对同一个 API 方法的 3 次调用。它们彼此独立。我怎样才能异步调用它们,以便一旦它们中的任何一个完成,我就可以对响应做一些事情,而不是等待其他的完成?寻找类似于 C# 中可用的 System.Threading.Tasks 的东西

var promise1 = $http.get("/api/city/boston");
promise1.success(function(name) {
   console.log("Your city is: " + name);
});

var promise2 = $http.get("/api/city/newyork");
promise2.success(function(name) {
   console.log("Your city is: " + name);
});

var promise3 = $http.get("/api/city/chicago");
promise3.success(function(name) {
   console.log("Your city is: " + name);
});

【问题讨论】:

  • 我很确定您提供的代码可以做到这一点。
  • 如果后端支持,AngularJS 框架将并行执行这些操作。顺便说一句,.success 方法一直是removed from the AngularJS framework

标签: javascript angularjs asynchronous


【解决方案1】:

您的代码将不起作用。您的变量是 promise1、promise2、promise3。但是在解决时,您只使用了 promise.resolve。

其次,你应该使用 then 而不是 success。如下所示

$http.get(url).then(function(response){
    //do something with the response.
 });

【讨论】:

    【解决方案2】:

    使用 angular 的 $q.race() 表示第一个已完成,$q.all() 表示所有已完成。

    您还可以使用函数和映射请求承诺数组来简化请求。

    另请注意,success() 已弃用


    类似:

    const getCityData = (city) => {
       return $http.get(`/api/city/${city}`).then(res => res.data)
    }
    
    const requestPromises = ['boston','newyork','chicago'].map(getCityData);
    
    $q.race(requestPromises).then(data => console.log('First one completed ', data));
    
    $q.all(requestPromises).then(dataArray => console.log('All completed', dataArray ))
                           .catch(err => console.log('Something failed', err)
    

    确保在您运行它的控制器或服务中注入 $q 服务。

    $q docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-08
      • 2012-07-25
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多