javascript - 等待异步函数在 Angular 中完成

标签 javascript angular asynchronous

所以我在 Angular 和 ngOninit 中开发一个新组件,我在下面有以下异步函数......

This.getUserProfile 需要在调用 this.getPrivateGroup() 之前完成,而 this.getPrivateGroup() 需要在调用 this.loadGroupPosts() 之前完成。我知道我可以在异步请求的回调中编写这些函数,但我想知道是否有办法将它保留在 ngOnInit 中以使其更干净?

有人有想法吗?

ngOnInit() {

    this.getUserProfile();

    // my-workplace depends on a private group and we need to fetch that group and edit
    // the group data before we proceed and get the group post
    if (this.isItMyWorkplace) {
      this.getPrivateGroup();
    }
    this.loadGroupPosts();
  }

getUserProfile() {
    this._userService.getUser()
      .subscribe((res) => {
        this.user = res.user;
        console.log('log user', this.user);
        this.profileImage = res.user['profile_pic'];
        this.profileImage = this.BASE_URL + `/uploads/${this.profileImage}`;
      }, (err) => {
        this.alert.class = 'alert alert-danger';
        if (err.status === 401) {
          this.alert.message = err.error.message;
          setTimeout(() => {
            localStorage.clear();
            this._router.navigate(['']);
          }, 3000);
        } else if (err.status) {
          this.alert.class = err.error.message;
        } else {
          this.alert.message = 'Error! either server is down or no internet connection';
        }
      });
  }



getPrivateGroup() {
    console.log('user check', this.user);
    this.groupService.getPrivateGroup(`${this.user.first_name}${this.user.last_name}`)
      .subscribe((group) => {
          console.log('received response', group)
    })
  }

 // !--LOAD ALL THE GROUP POSTS ON INIT--! //
  loadGroupPosts() {
    this.isLoading$.next(true);

    this.postService.getGroupPosts(this.group_id)
      .subscribe((res) => {
        // console.log('Group posts:', res);
        this.posts = res['posts'];
        console.log('Group posts:', this.posts);
        this.isLoading$.next(false);
        this.show_new_posts_badge = 0;
      }, (err) => {
        swal("Error!", "Error while retrieving the posts " + err, "danger");
      });
  }
  // !--LOAD ALL THE GROUP POSTS ON INIT--! //

最佳答案

您可以将基本 promise 与 async/await 结合使用。

async ngOnInit() {

    await this.getUserProfile(); // <-- 1. change

    // my-workplace depends on a private group and we need to fetch that group and edit
    // the group data before we proceed and get the group post
    if (this.isItMyWorkplace) {
      this.getPrivateGroup();
    }
    this.loadGroupPosts();
  }

async getUserProfile() {
    this._userService.getUser()
      .subscribe((res) => {
        this.user = res.user;
        console.log('log user', this.user);
        this.profileImage = res.user['profile_pic'];
        this.profileImage = this.BASE_URL + `/uploads/${this.profileImage}`;
        return true; // <-- this
      }, (err) => {
        this.alert.class = 'alert alert-danger';
        if (err.status === 401) {
          this.alert.message = err.error.message;
          setTimeout(() => {
            localStorage.clear();
            this._router.navigate(['']);
          }, 3000);
        } else if (err.status) {
          this.alert.class = err.error.message;
        } else {
          this.alert.message = 'Error! either server is down or no internet connection';
        }
        throw err;
      });

关于javascript - 等待异步函数在 Angular 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53817629/

相关文章:

jSTL 迭代中的 JavaScript

javascript - 同上 HTTP API 服务器发送事件 CORS 错误

javascript - 范围问题 : Array is not passed into promise resolution

java - 如何在 android 的异步函数中连续接收 UDP?

javascript - 是否可以在函数内更新间隔计时器?

angular - 为什么要在 Angular 模块中声明组件

javascript - Angular 8自动触发点击事件不起作用

javascript - Django 对 Angular $http 的响应未呈现为 angularjs 元素

c# - 此 MSDN 示例中 Lazy<T> 的用途

javascript - 了解 JavaScript 中另一个函数的 ajax 调用结果