What is the most up to date method to ensure that some asynchronous code completes in a class constructor before that class is subsequently used?
Specifically, how would an API client class retrieve an access token before allowing more method calls, as shown below?
class API_Client {
constructor(...) {
# Below should 'block' other method calls until token is assigned
this.login().then(res => {
this.token = res.data.token;
});
}
async login() {
return makeRequest(...) # <-- Promise which returns access token data
}
}
const client = new API_Client(...);
client.someAuthOnlyMethod() # <-- Should only happen after the `login` method completes.
I found older answers, yet couldn't quite understand how to solve the problem posed in the first comment left on the linked answer.