我如何在 for 循环中按顺序链接 promises,我在谷歌上看到很多这样做的例子,但我无法针对我的情况实现: 我经历过这个link用于 Promise 的顺序链接。
我想要达到的目标:
Promise1: 登录();
promise 2:同步();
sync 函数为元素数组调用另一个服务 complete()。这些元素数组必须按顺序完成。
ServiceA.login().
then(function(response){
ServiceA.sync()
.then(function(response){
})
})
function sync(){
ServiceB.complete()
.then(function(){
var promises = [];
angular.forEach(response, function (value) {
// The below service call doSomething() must be done sequentially for each "value"
promises.push(doSomething(value));
});
$q.all(promises).then(function () {
});
});
})
}
如何捕获每个 Promise 中发生的错误?
更新:
我已经使用以下代码尝试了@zaptree 建议的方法:
ServiceA.login()
.then(function(response){
// you must always return your promise
return ServiceA.sync()
})
// don't nest the .then make them flat like this
.then(function(response){
})
.catch(function(){
// if you made sure to always return your promises this catch will catch any errors throws in your promise chain including errors thrown by doSomething()
});
function sync(){
// you must always return your promise
return ServiceB.complete()
.then(function(){
var result = $q.when();
angular.forEach(response, function (value) {
result = result.then(doSomething(value)); // problem is here that doSomething function is being called before the first call it is resolved
// doSomething is a http call.
});
return result;
})
.then(function(){
// the array of promises has run sequentially and is completed
});
function doSomething(data){
return $http({
method: 'POST',
url: '/api/do',
data: data,
headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
}, function (error) {
});
}
如果 for each 循环附近的响应中有 2 个值 (valuea, valueb),则代码的行为如下:
1. 调用 doSomething(valuea)
2. 在上面的 promise 被解决之前调用 doSomething(valueb)。
预期行为:
在通过调用 doSOmething(valuea) 成功完成 POST 方法之后,应该会发生另一个 POST 调用,即 soSomething(valueb)。
最佳答案
这是我想出的。您需要将数组缩减为单个 promise 。
var results = [...];
var sequentialPromise = results.reduce(function(a, b) {
return a.then(function(){
return doSomething(b);
});
}, $q.resolve());
sequentialPromise.then(function(){...});
关于javascript - AngularJS 链在 for 循环中按顺序 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272992/