繁体   English   中英

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

[英]Wait for async method to execute before iterating forEach loop: Angular 4

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

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

在上面,我想添加一个逻辑,直到setUserInfo()完成,该逻辑才为循环增加。

注意:我使用的是Lodash 4的forEach方法,因此请忽略其他语法。

这是两种实现结果的方法(即不使用单独的http服务以将所有代码都放在一个位置)

with promise是第一个解决方案,其中im使用es5中的async await函数。 我正在创建循环,在该循环中,我等待循环中的调用结果,并且仅在下一个请求被调用之后。

使用observables ,第二个解决方案更加对angularDev友好,并使用rxjs Subject ,它是在Subject实例上调用.next()方法时发出事件的对象。 重要的是要注意,我们必须在某个时候取消订阅主题,否则我们将陷入无限循环,这并不酷,还请注意,我正在使用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("im the first line"); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM