gpt4 book ai didi

javascript - Angular : How do I execute an array of defered in order?

转载 作者:行者123 更新时间:2023-11-29 16:14:14 27 4
gpt4 key购买 nike

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

$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

最佳答案

为简洁起见,使用 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.
});

关于javascript - Angular : How do I execute an array of defered in order?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19844052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com