在最后一次使用该类之前,确保某些异步代码在类构造函数中完成的最新方法是什么?
具体来说,API客户端类在允许更多方法调用之前如何检索访问令牌,如下所示?
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.
我找到了older answers,但还不太明白如何解决链接答案留下的第一条评论中提出的问题。
答案 0 :(得分:2)
最新方法仍为not to put any asynchronous stuff in the constructor。在您的具体情况下,那是
class API_Client {
constructor(token) {
this.token = token;
}
static async createLoggedIn(…) {
const res = await makeRequest(...) # <-- Promise which returns access token data
return new this(res.data.token);
}
}
const client = await API_Client.createLoggedIn(…);
client.someAuthOnlyMethod()
答案 1 :(得分:1)
您可以将令牌存储为承诺:
class API_Client {
constructor(...) {
# Below should 'block' other method calls until token is assigned
this.token = this.login()
.then(res => res.data.token)
}
async someAuthOnlyMethod() {
let token = await this.token;
//...continue
}
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.
答案 2 :(得分:-1)
您不应该从构造函数中调用任何异步代码。在上面的例子中,您的makeRequest函数会担心登录令牌。
在这种情况下,课堂上也没有实际价值。您应该只导出一系列函数来进行API调用。