我有一系列需要按顺序运行的 promise 。
var promises = [promise1, promise2, ..., promiseN];
调用 RSVP.all 将并行执行它们:
RSVP.all(promises).then(...);
但是,我怎样才能按顺序运行它们呢?
我可以像这样手动堆叠它们
RSVP.resolve()
.then(promise1)
.then(promise2)
...
.then(promiseN)
.then(...);
但问题是 promise 的数量是变化的,而且 promises 的数组是动态构建的。
最佳答案
如果您已经将它们放在数组中,那么它们已经在执行。如果你有一个 promise ,那么它已经在执行了。这不是 promises 的问题(即在 .Start()
方法方面,它们不像 C# Task
)。 .all
不执行任何操作
它只是返回一个 promise 。
如果你有一组 promise 返回函数:
var tasks = [fn1, fn2, fn3...];
tasks.reduce(function(cur, next) {
return cur.then(next);
}, RSVP.resolve()).then(function() {
//all executed
});
或值(value)观:
var idsToDelete = [1,2,3];
idsToDelete.reduce(function(cur, next) {
return cur.then(function() {
return http.post("/delete.php?id=" + next);
});
}, RSVP.resolve()).then(function() {
//all executed
});
关于javascript - 如何按顺序执行 promise 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20100245/