![](/img/trans.png)
[英]javascript how to use make process wait until async function finishes
[英]Angular fire 2 async calls at once but do not process the second callback until the first finishes
我正在使用Angular的$ q服務來發出異步請求。 我有2個這樣的請求(假設我有一個名為MyService的角度服務來處理這些請求):
MyService.Call1().then(function() {
//do all the first callback's processing here without waiting for call 2
});
MyService.Call2().then(function() {
//wait for results of first callback before executing this
});
我不能保證第二次調用會在第一次調用之后完成,但我需要調用1的結果才能在調用2中進行處理。我知道我可以將promises鏈接在一起,這意味着調用2等待調用1到在請求完成之前完成,但我想同時觸發兩個請求,因為我有所需的所有數據。 最好的方法是什么?
編輯:我可以立即使用第一個調用的結果。 他們在我的頁面上開了一些圖表。 我不希望第一次調用等待第二次調用來進行處理。 我認為這排除了$ q.all()等機制
您可以與all
並行執行兩個呼叫
$q.all([MyService.Call1(), MyService.Call2()]).then(function() {
// ...code dependent on both calls resolving.
});
編輯 :在回復評論時,您可能會對兩件事感興趣。 如果你傳遞一個數組all
,你會發現分辨率為你的函數內的第一個參數的數組then
。 相反,如果你將一個對象傳遞給all
,你會發現一個對象作為你的第一個參數,其中的鍵與你傳遞給all
鍵的鍵相同。
$q.all([MyService.Call1(), MyService.Call2()]).then(function(arr) {
// ...code dependent on the completion of both calls. The result
// of Call1 will be in arr[0], and the result of Call2 will be in
// arr[1]
});
......和對象
$q.all({a: MyService.Call1(), b: MyService.Call2()}).then(function(obj) {
// ...code dependent on the completion of both calls. The result
// of Call1 will be in abj.a, and the result of Call2 will be in
// obj.b
});
使用$q.all
的另一種方法是在第二個處理程序中使用第一個promise。 例如
var p1 = MyService.Call1().then(function(data) {
return processedData;
});
MyService.Call2().then(function(call2Data) {
return p1.then(function(call1Data) {
// now you have both sets of data
});
});
為了解決一些意見,這里是你能怎么處理錯誤/而不必等待所有承諾解決或創建多個承諾拒絕catch
處理程序...
var p2 = MyService.Call2().then(function(call2Data) {
return p1.then(function(call1Data) {
// now you have both sets of data
});
});
// use `$q.all` only to handle errors
$q.all([p1, p2]).catch(function(rejection) {
// handle the error here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.