我有一个项目数组,在每个元素上,我要进行一个HTTP调用,等待它完成,然后进行另一个调用,每次只调用一个。
我试过:
index(item) {
return this.service.index(item).pipe(
map(response => {
// handle success case
}),
catchError(error => {
// handle error case
})
)
}
async processArray(array) {
const promises = array.map(item => this.index(item));
await Promise.all(promises);
}
proccessArray(array);还有NGRX效应:
@Effect()
effect$ = this.actions$.pipe(
ofType<action>(actionTypes.action),
mergeMapTo(this.store.select(getMyArray)),
flatMap((request: any[]) => {
return zip(...request.map(item => {
return this.service.index(item).pipe(
map(response => {
// handle success case
}),
catchError(error => {
// handle error case
})
)
}))
}),
);还尝试在for和forEach循环中执行该操作,但它们同时触发了所有请求。我怎样才能做到这一点?
发布于 2018-12-25 15:32:18
如果您使用的是承诺,并且希望在进行另一个调用之前等待每个承诺解决,那么(1)您不应该使用Promise.all,因为这将等待所有请求被解析;(2)您需要使用一个普通的旧for -循环,它使您能够等待循环中的异步操作。
async processArray(array) {
for(var i = 0; i < array.length; i++){
await yourServiceCall();
}
}作为一个侧面:由于您使用异步等待,不要忘记转换您的观察到承诺。
如果您想摆脱承诺(和异步等待),转而依赖纯RxJS,请查看concatMap。
将每个源值投影到可观察到的输出中,并以序列化的方式将其合并到可观察的输出中,等待每个源值在合并下一个源值之前完成。
例如:
import { from } from 'rxjs/observable/from';
ngOnInit() {
from(myArray)
.pipe(concatMap(el => yourServiceCall(el)))
.subscribe(/* your logic */);
}https://stackoverflow.com/questions/53923003
复制相似问题