遇到了 angularjs 和一些 promise 的问题。出于某种原因,我的服务混合了查询的答案,虽然服务是固定的,但我需要将我的 $q.all() 更改为 按顺序运行,而不是异步运行所有 promise 。
现在,它看起来像这样:
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 文档并找到了 a sequence reference但不能让它与 $q 一起工作。
任何人都可以为此类问题推荐一个简单的解决方案吗?
我试过这个 promises.reduce($q.when, $q(initialVal));
但不明白 initialVal 指的是什么 :(
感谢阅读,祝您有愉快的一天。
最佳答案
如果您已经有 promise ,则异步方法已被触发!您必须一个接一个地触发它们,因此您的数组需要包含返回 promises 而不是 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.
});
关于javascript - Angularjs $q 按顺序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32758562/