Angularjs $q按顺序运行

Angularjs $q run in sequences

本文关键字:顺序 运行 Angularjs      更新时间:2023-09-26

angularjs和一些承诺有问题。由于某种原因,我的服务在查询时混合了答案,虽然服务是固定的,但我需要更改我的$q.all(),而不是异步运行所有承诺,依次运行

现在,它看起来是这样的:

var promises = [p1, p2, p3];
$q.all(promises).then(function () {
    // All promises are done
}).catch(function (exception) {
    // An error occured.
});

期望的行为应该像p1.then(p2).then(p3);,顺序无关紧要(因为通常运行异步)。数组长度是可变的

由于$q是受q库的启发,我在q文档中找到了一个序列引用,但无法使它与$q一起工作。

有谁能建议一个简单的解决方案吗?

我确实尝试过这个promises.reduce($q.when, $q(initialVal));,但不明白initialVal指的是什么:(

感谢您的阅读,祝您愉快。

如果你已经有了承诺,异步方法已经被触发了!你必须一个一个地触发它们,所以你的数组需要包含返回promise的函数,而不是promise对象。

你可以这样做,这比你在问题中提供的Q的快捷方式更清楚:

var promiseReturningFunctions = [p1, p2, p3];
var queueEntryPoint = $q.defer();
// create a waiting queue
var queue = queueEntryPoint.promise;
// this queues up the asynchronous functions
promiseReturningFunctions.forEach(function (p) {
    queue = queue.then(p);
});
// here we start processing the queue by resolving our queueEntryPoint
queueEntryPoint.resolve();
// we can now use queue.then(...) to do something after all promises in queue were resolved
queue.then(function () {
    // All promises are done
}).catch(function (exception) {
    // An error occured.
});