简体   繁体   English

在构造函数或ngOnInit中加载异步函数

[英]Loading an async function in constructor or ngOnInit

I want to call a async function readUsers() within the constructor or ngOnInit(). 我想在构造函数或ngOnInit()中调用异步函数readUsers()。 Although I used a recommended workaraound from here it still is delayed and does not wait in execution. 虽然我从这里使用了推荐的工作手册,但它仍然被延迟,并且不会等待执行。

async constructor functions in TypeScript? TypeScript中的异步构造函数?

How can I delay/wait with execution of my readUsers() function? 如何延迟/等待执行readUsers()函数?

users: any[];

ngOnInit() {
    this.readUsers();
    //this.readUsers(); above is called delayed so this.users below is 
    //undefined
    console.log(this.users);
}


public readUsers = async () =>  {
    this.users = await this.userService.getUsers()
    .then(resolve=>{
        console.log("within async function");
        return resolve;
    })
    .catch(reject=>{
        return [];
    })
}


////////userService.getUsers() reads JSON Object from an endpoint (works!)
getUsers(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.http
            .get('https://url.com/users/')
            .subscribe(users => {
                if (!users) {
                    reject([]);
                }
                resolve(users);
            });
    });
}

The console.log is switched as there is no waiting: console.log被切换,因为没有等待:

undefined 未定义

within async function 在异步功能中

interface OnInit {
  ngOnInit(): void
}

When something returns a void, then you can generally convert it to a Promise without any side-effects 当某些东西返回空白时,你通常可以将它转换为Promise而没有任何副作用

async ngOnInit(): Promise<void> {
    await this.readUsers();
    console.log(this.users);
}

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

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