首页 > 解决方案 > AngularJS:在单个函数中等待多个异步调用

问题描述

我有一个 AngularJS 函数,我在其中进行了 2 个异步调用。2 个调用不依赖,但该函数仅应在两个调用都完成且结果存储在 return var 时返回。

我尝试了不同的解决方案,最终使用了如下所示的解决方案。但是它非常慢,因为它等待第一个完成

        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;
    }

调用函数

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

如何在不嵌套它们的情况下等待同一函数中的两个调用?或者在不等待第一个完成的情况下调用下一个。

标签: javascriptangularjsasynchronouspromiseangular-promise

解决方案


  1. 我认为您的情况最适合使用$q.all([promise1, promise2, promise3]).then()语法。
  2. msGraph.getClient()多次打电话,我认为这是可以避免的。

推荐阅读