等待异步方法执行,然后再迭代每个循环:Angular 4



我正在调用一个正在执行一些异步操作的方法,我想在迭代循环之前等待这些方法完成,以便异步操作按顺序完成。但我很难理解如何实现这一目标。这是我正在做的事情:

_.forEach(this.pendingUsers.queue, (user) => {
this.myService.setUserInfo(user);
});

在上面,我想添加一个逻辑,在 setUserInfo(( 完成之前不会递增循环。

注意:我使用的是 Lodash 4 的 forEach 方法,所以请忽略不同的语法。

这里有两种方法可以实现结果(我不使用单独的http服务,以便将所有代码保存在一个地方(

有了 to promise是第一个解决方案,其中 im 使用 es5 中的异步 await 函数。我创建循环,在该循环中,我等待循环中调用的结果,然后才调用下一个请求。

对于可观察量,第二种解决方案对 angularDev 更友好,并且正在使用rxjsSubject该对象,该对象在Subject实例上调用.next()方法时发出事件。这里需要注意的是,我们必须在某个时候从主题中取消订阅,否则我们将陷入无限循环,这并不酷,还要注意im使用first()运算符以避免未处理的订阅

这是一个现场演示 CodeSandbox *看控制台

import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { first } from "rxjs/operators";
import { Subject } from "rxjs/Subject";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "CodeSandbox";
dumySubject = new Subject();
constructor(private http: HttpClient) {}
ngOnInit() {
let currentIndex = 1;
//With toPromise
let indexes = [1, 2, 3, 4];
let someFunc = async () => {
for (const id of indexes) {
let someResp = this.http
.get("https://jsonplaceholder.typicode.com/posts/" + id)
.toPromise()
.then(x => {
console.log(x);
});
await someResp;
console.log("___");
}
};
someFunc();
//With observables
let sub = this.dumySubject.subscribe(x => {
console.log("in");
if (currentIndex > 5) {
sub.unsubscribe();
}
this.http
.get("https://jsonplaceholder.typicode.com/posts/" + currentIndex)
.pipe(first())
.subscribe(x => {
console.log(x);
console.log("________");
currentIndex++;
this.dumySubject.next();
});
});
this.dumySubject.next();
console.log("i m the first line");
}
}

最新更新