繁体   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