2

我有一组异步函数,如果前一个函数已经解决,那么运行一个函数才有意义。您可以将它们视为对不同 URL 的 HTT 获取请求,例如

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

我怎样才能序列化它们?

编辑:数组中有 N 个。所以我不能明确地展开它们并用'then'加入它们,例如:

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 
4

3 回答 3

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.
});
于 2015-04-21T02:23:28.707 回答
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
})
于 2013-11-07T18:50:39.600 回答
0

您的数组需要包含您要使用的数据,并且在前一个承诺解决后完成的函数调用。您可以通过将调用放在函数内部来调整@Esailija 的解决方案cur.then,但是这样做的惯用方法是[].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

于 2013-11-09T19:24:38.363 回答