AngularJS链在for循环中按顺序承诺 [英] AngularJS chain promises sequentially within for loop

查看:66
本文介绍了AngularJS链在for循环中按顺序承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何在for循环中按顺序链接promise,我已经在Google上看到了很多示例来做到这一点,但是我无法为我的情况实现:我已经通过链接进行了Promises的顺序链接.

How do i chain promises sequentially within for loop, i have seen lot of examples on google to do this but i couldn't implement for my case: i have gone through this link for sequential chaining of Promises.

我要达到的目标:
承诺1:login();
Promise2:sync();

What I'm trying to acheive:
Promise1: login();
Promise2: sync();

sync函数为元素数组调用另一个服务complete().这些元素数组必须按顺序完成.

sync function calls another service complete() for an array of elements. These array of elements must be done sequentially.

ServiceA.login().  
      then(function(response){
                   ServiceA.sync()
                        .then(function(response){

                         })
      })

function sync(){
     ServiceB.complete()
                    .then(function(){
                               var promises = [];
                               angular.forEach(response, function (value) {
                    // The below service call doSomething() must be done sequentially for each "value"
                                  promises.push(doSomething(value));
                               });
                               $q.all(promises).then(function () {


                                        });
                                    });

                      })
}

如何捕获每个Promise中发生的错误?

How do I capture the error occuring in each Promise?

更新:
我尝试了使用以下代码的@zaptree建议的方法:

Update:
I have tried the approach suggested by @zaptree with the following code:

ServiceA.login()
.then(function(response){
    // you must always return your promise
    return ServiceA.sync()

})
// don't nest the .then make them flat like this
.then(function(response){

})
.catch(function(){
    // if you made sure to always return your promises this catch will catch any errors throws in your promise chain including errors thrown by doSomething()
});

function sync(){
// you must always return your promise
return ServiceB.complete()
    .then(function(){

        var result = $q.when();
        angular.forEach(response, function (value) {
            result = result.then(doSomething(value)); // problem is here that doSomething function is being called before the first call it is resolved
// doSomething is a http call.
        });
        return result;
    })
    .then(function(){
        // the array of promises has run sequentially and is completed
    });

}

 function doSomething(data){
      return $http({
            method: 'POST',
            url: '/api/do',
            data: data,
            headers: {
                "Content-Type": "application/json"
            }
        }).then(function (response) {

        }, function (error) {

        });
  }

如果每个循环附近的响应中都有2个值(valuea,valueb),则代码的行为如下:
1.调用doSomething(valuea)
2.在上述承诺得到解决之前,调用doSomething(valueb).
预期的行为:
在通过doSOmething(valuea)调用成功完成POST方法后,应再进行一次POST调用,即soSomething(valueb).

If the response in the near the for each loop has 2 values (valuea, valueb) in it, the code is behaving as follows:
1. calling doSomething(valuea)
2. calling doSomething(valueb) before the above promise is resolved.
Expected behaviour:
after the POST method has succesfully completed by the call doSOmething(valuea), then the another POST call should happend i.e., soSomething(valueb).

推荐答案

这就是我的想法.您需要将数组简化为一个promise.

Here's what I came up with. You'll need to reduce the array into a single promise.

var results = [...];
var sequentialPromise = results.reduce(function(a, b) {
  return a.then(function(){
   return doSomething(b);
  });
}, $q.resolve());

sequentialPromise.then(function(){...});

这篇关于AngularJS链在for循环中按顺序承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆