簡體   English   中英

AngularJS:在單個 function 中等待多個異步調用

[英]AngularJS: Waiting for Multiple asynchronous calls in a single function

我有一個 AngularJS function 在其中進行了 2 個異步調用。 這兩個調用不依賴,但 function 應該只在兩個調用都完成並且結果存儲在返回變量中時返回。

我嘗試了不同的解決方案,最終使用了如下所示的解決方案。 但是它非常慢,因為它等待第一個完成

        function myAngularfunction(a, b) {
        var defer = $q.defer();
        var test= {
            a: "",
            b: ""
        };

        msGraph.getClient()
            .then((client) => {
                // First Async call
                client 
                .api("https://graph.microsoft.com/v1.0/")
                .get()
                 .then((groupResponse) => {
                        var result = groupResponse;
                        test.a= result.displayName;

                        msGraph.getClient()
                            .then((client) => {
                                // Second Async call
                                client
                                    .api("https://graph.microsoft.com/v1.0/teams/")
                                    .get()
                                    .then((groupResponse) => {
                                        var result = groupResponse;
                                        test.b= result.displayName;
                                        defer.resolve(test);
                                    });

                            });

                    });
            });


        return defer.promise;
    }

調用 function

myAngularfunction(a, b).then(function(obj)

如何在不嵌套它們的情況下等待同一個 function 中的兩個調用? 或者在不等待第一個完成的情況下調用下一個。

可能你可以像這樣嘗試 $when:$.when(functiton1,function2).done(()=>{})。 但您需要在 function1 和 function 2 中添加延遲。

  1. 我認為您的情況最適合使用$q.all([promise1, promise2, promise3]).then()語法。
  2. 您多次調用msGraph.getClient() ,我認為這是可以避免的。

暫無
暫無

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

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