简体   繁体   English

异步ES2017构造函数

[英]Async ES2017 Constructor

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? 具体来说,如下所示,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.

I found older answers , yet couldn't quite understand how to solve the problem posed in the first comment left on the linked answer. 我找到了较旧的答案 ,但还不太了解如何解决链接的答案的第一个注释中提出的问题。

The most up-to-date method is still not to put any asynchronous stuff in the constructor . 最新的方法仍然是不要在构造函数中放置任何异步内容 In your specific case, that's 在您的特定情况下,

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()

You could store the token as a promise: 您可以将令牌存储为承诺:

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.

You shouldn't be calling any asynchronous code from a constructor to begin with. 首先,您不应该从构造函数中调用任何异步代码。 In the case above, your makeRequest function would worry about the login token. 在上述情况下,您的makeRequest函数将担心登录令牌。

There is also no real value in a class in this case. 在这种情况下,一个类也没有实际价值。 You should just export a series of functions to make the API calls. 您应该只导出一系列函数来进行API调用。

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

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