簡體   English   中英

異步ES2017構造函數

[英]Async ES2017 Constructor

確保在隨后使用該類之前在類構造函數中完成一些異步代碼的最新方法是什么?

具體來說,如下所示,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.

我找到了較舊的答案 ,但還不太了解如何解決鏈接的答案的第一個注釋中提出的問題。

最新的方法仍然是不要在構造函數中放置任何異步內容 在您的特定情況下,

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

您可以將令牌存儲為承諾:

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.

首先,您不應該從構造函數中調用任何異步代碼。 在上述情況下,您的makeRequest函數將擔心登錄令牌。

在這種情況下,一個類也沒有實際價值。 您應該只導出一系列函數來進行API調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM