javascript - Angular fire 2 async 调用一次,但在第一个回调完成之前不处理第二个回调

标签 javascript angularjs asynchronous promise simultaneous

我正在使用 Angular 的 $q 服务来发出异步请求。我有 2 个这样的请求(假设我有一个名为 MyService 的 Angular 服务来处理这些请求):

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 中进行处理。我知道我可以将 promise 链接在一起,这意味着调用 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
});

关于javascript - Angular fire 2 async 调用一次,但在第一个回调完成之前不处理第二个回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30362777/

相关文章:

javascript - 多个文本框输入验证检查

javascript - 如何将 getChildContext 与功能组件一起使用

javascript - 此 JS/jQuery 代码在 Firefox 中有效,但在 Chrome 中无效

Javascript正则表达式将字符串解析为数字并进行一些计算

javascript - 异步加载到 body 中的 JS 使浏览器保持在 "loading"模式

c# - 异步初始化及其单元测试

c# - 为什么要在 C# 中使用 Task<T> 而不是 ValueTask<T>?

javascript - react : Access ref passed between components via render props

angularjs - 带有样式的 ng-bind-html 不起作用

javascript - 在 ng-grid Angular js 中加载不同的图像