简体   繁体   中英

Loading an async function in constructor or ngOnInit

I want to call a async function readUsers() within the constructor or ngOnInit(). Although I used a recommended workaraound from here it still is delayed and does not wait in execution.

async constructor functions in TypeScript?

How can I delay/wait with execution of my readUsers() function?

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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