簡體   English   中英

多次異步調用同一個 API function AngularJS 參數不同

[英]Multiple asynchronous calls to the same API function with different parameters in AngularJS

考慮對同一 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);
});

您的代碼將不起作用。 您的變量是 promise1、promise2、promise3。 但是在解析時,您只使用了 promise.resolve。

其次,您應該使用 then 而不是 success。 像下面

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

使用角度的$q.race()完成第一個,使用$q.all()完成所有完成。

您還可以使用 function 並映射請求承諾數組來簡化請求。

另請注意,不推薦使用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)

確保在 controller 或運行它的服務中注入$q服務。

$q 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM