我有可链接的promise,在一个系列中都可以正常工作,但是现在我想在for loop中调用chain的这个serios,但是它不能按预期的方式工作。
请参阅我的演示插件,并在控制台中查看输出。
以下是我的链接承诺的结构。我希望所有的publicIP由返回funTwo
;但是我想完成funThree()
然后想要获得所有publicIP。据我所知,这$q.when()
在Promise对象中很有价值。
但是你可以看到,console.log('pA', promiseArray);
非常之前执行,console.log('res three');
以及为什么successHandler
和finally
之前叫什么?
在这里,我肯定会丢失一些东西,可能必须return;
在适当的位置写一个,请帮助我如何在for循环中执行所有功能,并在for循环结束后返回一个可以重试的数据数组。successHandler
MyService.funZero()
.then(function(response) {
console.log(response);
var promiseArray = [];
for(var i = 0; i < 2 ; i++) {
console.log('I', i);
MyService.funOne()
.then(MyService.funTwo)
.then(function(res2) {
console.log('res two', res2);
publicIP = res2.ip;
console.log('i', publicIP);
promiseArray.push({'ip': publicIP});
return MyService.funThree(publicIP);
})
.then(function() {
console.log('res three');
})
} // for loop ends
console.log('pA', promiseArray);
return $q.when(promiseArray);
})
.then(function(res4){
console.log('after for loop', res4);
})
.then(successHandler)
.catch(errorHandler)
.finally(final, notify);
因此,我不确定MyService.funThree到底是做什么的,但是您可以通过聚合一个数组,然后将其ipArray.push({'ip': publicIP})
返回给MyService.funThree
然后是后续函数。ipArray
如果您要寻找的是这里的问题,就不能保证订单的顺序。这是该函数的中间部分:
ipArray = [];
for(var i = 0; i < 2 ; i++) {
console.log('I', i);
var promise = MyService.funOne()
.then(MyService.funTwo)
.then(function(res2) {
console.log('res two', res2);
publicIP = res2.ip;
console.log('i', publicIP);
ipArray.push({'ip': publicIP});
return ipArray;
})
.then(MyService.funThree)
.then(function() {
console.log('res three');
});
promiseArray.push(promise);
}
console.log('pA', promiseArray);
return $q.all(promiseArray);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句