Angular fire 2异步调用一次,但在第一次完成之前不处理第二次回调

时间:2015-05-21 00:52:19

标签: javascript angularjs asynchronous promise simultaneous

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

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中进行处理。我明白我可以将承诺链接在一起,这意味着第2个呼叫等待在请求发出之前调用1完成,但我想同时触发两个请求,因为我有所需的所有数据。最好的方法是什么?

编辑:我可以立即使用第一个电话的结果。他们在我的页面上开了一些图表。我不希望第一次调用等待第二次调用来进行处理。我认为这排除了像$ q.all()

这样的机制

2 个答案:

答案 0 :(得分:3)

您可以与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
});

答案 1 :(得分:1)

使用$q.all的另一种方法是在第二个处理程序中使用第一个promise。例如

var p1 = MyService.Call1().then(function(data) {
    return processedData;
});

MyService.Call2().then(function(call2Data) {
    return p1.then(function(call1Data) {
        // now you have both sets of data
    });
});

要解决一些意见,请按照 处理错误/承诺拒绝的方式,而不必等待两个承诺解决或创建多个catch处理程序...... < / p>

var p2 = MyService.Call2().then(function(call2Data) {
    return p1.then(function(call1Data) {
        // now you have both sets of data
    });
});

// use `$q.all` only to handle errors
$q.all([p1, p2]).catch(function(rejection) {
    // handle the error here
});