javascript - 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)
如何在不嵌套它们的情况下等待同一函数中的两个调用?或者在不等待第一个完成的情况下调用下一个。
解决方案
- 我认为您的情况最适合使用
$q.all([promise1, promise2, promise3]).then()
语法。 - 你
msGraph.getClient()
多次打电话,我认为这是可以避免的。
推荐阅读
- jquery - 使用 jquery clone() 在输入字段中生成一个新的 bootstarp Tokenfield 类
- angularjs - 如何在 phoenix 中使用嵌套表单关联?
- angular - Angular 6 模板驱动表单中的 DOB 验证
- javascript - 仅为被点击的 div 设置 contentEditable="true",其余为 false
- python - QWebEngineView 让我们的样式表边框消失
- asp.net - IIS 8.0 中的 URL 重定向
- php - 如何在 Mysqli 中将 UNION 中的结果与 IN 子句绑定?
- c# - 如何发布 NULL 值 C#
- java - 每当应用程序打开时重新启动 AlarmManager
- python-3.x - 模块在 IDE 上运行,但不会编译为 EXE