簡體   English   中英

我如何“等待”異步 super() 構造函數?

[英]How can i "await" async super() constructor?

我正在嘗試使用 NodeJS 中的 PayPal API REST,所以我必須使用 Axios 進行異步調用,但是我在分離的類上執行此操作,我有兩個類:

const axios = require("axios");

/**PayPal main class, this class will setup PayPal credentials when instance */
class PayPal {

   constructor() {
        return new Promise(async (resolve, reject) => {
            await this.setupEnvironment();
            resolve();
        });
    }

    setupEnvironment = async () => {
        
        // Sets base URL to send requests
        this.setAPIDomain();

        // Sets PayPal endpoints
        this.setPayPalEndpoints();

        // Sets API Keys
        await this.setAPIKeys();

    }

    setAPIKeys = async () => {

        const paypal_credentials = this.getPayPalCredetials();
        const { client_id, client_secret } = paypal_credentials;

        try {

            const response = await axios({
                method: "post",
                url: this.endpoints.get_access_token,
                data: "grant_type=client_credentials",
                headers: {
                  "Accept-Language": "en_US",
                  "Accept": "application/json"
                },
                auth: {
                    username: client_id,
                    password: client_secret
                },
            });

            this.access_token = response.data.access_token;
            
        } catch (error) {
            console.log(error.response.data);
            throw new Error(error.response.data.error_description);
        }


    }

}

class Customer extends PayPal() {

    constructor() {
        super();
        // Customer class do some others actions
    }

}


$paypal_gateway = new Customer();

如您所見,在 PayPal 類中有一個方法 (setAPIKeys),它向 PayPal 發送請求以生成 mi 訪問令牌,如果我放置了一個console.log(this.access_token)我正在獲取我的訪問令牌,但它只是如果我把它放在 setAPIKeys 方法中(我在這里省略了這個類的一些方法),就會發生這種情況。

如果我把console.log($paypal_gateway.access_token)我變得未定義,這很明顯,因為 PayPal 類構造函數正在返回一個承諾,但在 Customer 類構造函數中,我只是調用super()方法而沒有異步方式,我試圖將“異步”放在 super() 的左側,但它不起作用,我也試過這個:

class Customer extends PayPal {

    constructor() {

        return new Promise(async (resolve, reject) => {
            // Call to parent constructor
            super();

            // Set Customer properties
            this.setCustomer();
            resolve();
        });

    }

}

但也不起作用,如果我在 super() 函數下放置一個console.log(this.access_token)我也未定義,所以我不知道我能做些什么來等待這個 super() 構造函數,你能幫我嗎?

構造函數必須返回一個對象——特別是它在其中定義的類的一個實例。它不能返回一個 Promise,這是異步函數所做的。 您必須執行一個設置步驟。 您可以創建一個異步工廠函數來實例化對象並執行所有設置步驟,並返回結果對象。

async function createPaypal {
  const paypal = new PayPal()
  await paypal.setupEnvironment()
  return paypal;

}

我在@sdgluc 注釋的幫助下解決了這個問題,我避免了構造函數方法並實現了一個異步 init 方法:

const axios = require("axios");

/**PayPal main class, this class will setup PayPal credentials when instance */
class PayPal {

    setupEnvironment = async () => {
        
        // Sets base URL to send requests
        this.setAPIDomain();

        // Sets PayPal endpoints
        this.setPayPalEndpoints();

        // Sets API Keys
        await this.setAPIKeys();

    }

    setAPIKeys = async () => {

        const paypal_credentials = this.getPayPalCredetials();
        const { client_id, client_secret } = paypal_credentials;

        try {

            const response = await axios({
                method: "post",
                url: this.endpoints.get_access_token,
                data: "grant_type=client_credentials",
                headers: {
                  "Accept-Language": "en_US",
                  "Accept": "application/json"
                },
                auth: {
                    username: client_id,
                    password: client_secret
                },
            });

            this.access_token = response.data.access_token;
            
        } catch (error) {
            console.log(error.response.data);
            throw new Error(error.response.data.error_description);
        }


    }

}

class Customer extends PayPal() {

    async init = () => {
        await this.setupEnvironment();
        // More init code
    }

}

const paypal_gateway = new Customer();
await paypal_gateway.init(); // <- code inside another async function

希望這對其他人有所幫助,非常感謝!

暫無
暫無

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

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