AngularJS:如何按顺序执行延迟数组?

时间:2013-11-07 18:42:00

标签: javascript angularjs promise deferred

我有一组异步函数,只有在前一个函数被解析后运行一个才有意义。您可以将它们视为HTT获取对不同URL的请求,例如

$http.get('/step1')
$http.get('/step2')
$http.get('/step3')
$http.get('/step4')

我如何序列化它们?

编辑:阵列中有N个。因此,我无法明确地展开它们并将它们加入'然后',例如:

var calls = Array()

for(var i = 0; i < N; i++)
{
    var d = $q.defer();

    ...

    calls.push(d.promise);
}

..

// How to do resolve the elements of 'calls' in order?

编辑2:

我想:

Running Step #0 
Step completed: #0 OK 
Running Step #1 
Step completed: #1 OK 
Running Step #2 
Step completed: #2 OK 
Running Step #3 
Step completed: #3 OK 
Running Step #4 
Step completed: #4 OK 
Running Step #5 
Step completed: #5 OK 

Running Step #0 
Running Step #1 
Running Step #2 
Running Step #3 
Running Step #4 
Running Step #5 
Step completed: #0 OK 
Step completed: #1 OK 
Step completed: #2 OK 
Step completed: #3 OK 
Step completed: #4 OK 
Step completed: #5 OK 

3 个答案:

答案 0 :(得分:4)

使用lodash简洁。

_.reduce(_.rest(calls), function(promise, call) {
  return promise.then(function() {
    return call();
  });
}, _.first(calls)()).then(function() {
  // do something after they are all done sequentially.
});

答案 1 :(得分:2)

var cur = $q.when();
var promises = [$http.get('/step1'), $http.get('/step2'), ...];

promises.forEach(function(promise){
    cur = cur.then(function(){
        return promise;
    });
})

cur.then(function(){
    //All done
})

答案 2 :(得分:0)

您的数组需要包含您要使用的数据,并且在前一个承诺解决后完成函数调用。您可以通过将调用放在cur.then函数中来调整@ Esailija的解决方案,但是惯用的方法是使用[].reduce

var urls = ["/step1", "/step2", "step3"];

var done = urls.reduce(function (previous, url) {
    return previous.then(function () {
        return $http.get(url);
    });
}, $q.when());

done.then( ... );

见Kris Kowal的Qooqbooq