2

前の関数が解決されている場合にのみ実行するのが理にかなっている非同期関数の配列があります。これらは、別の URL への HTT get 要求と考えることができます。

$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 に答える
0

配列は使用したいデータである必要があり、関数呼び出しは前の約束が解決された後に行われます。関数内に呼び出しを配置することで @Esailja のソリューションを適応させることができますが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 に答える