我有一个项目数组,我想对每个元素进行 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
循环中执行此操作,但它们会同时触发所有请求。我怎样才能做到这一点?
最佳答案
如果您正在使用 promises 并希望在进行另一个调用之前等待每个 promise 解决,那么 (1) 您不应该使用 Promise.all因为这将等到所有请求都得到解决,并且 (2) 您需要使用一个普通的旧 for 循环,它使您能够等待循环内的异步操作。
async processArray(array) {
for(var i = 0; i < array.length; i++){
await yourServiceCall();
}
}
作为旁注:由于您正在使用异步等待,请不要忘记 convert你对 promise 的观察。
如果您想摆脱 promises(和 async-await)并转而依赖纯 RxJS,请查看 concatMap :
Projects each source value to an Observable which is merged in the output Observable, in a serialized fashion waiting for each one to complete before merging the next.
例如:
import { from } from 'rxjs/observable/from';
ngOnInit() {
from(myArray)
.pipe(concatMap(el => yourServiceCall(el)))
.subscribe(/* your logic */);
}
关于javascript - 如何在循环内进行 HTTP 调用并等待一个完成后再进行另一个调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53923003/