Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript “我怎么能?”;等待“;异步超级()构造函数?_Javascript_Node.js_Class_Constructor_Async Await - Fatal编程技术网

Javascript “我怎么能?”;等待“;异步超级()构造函数?

Javascript “我怎么能?”;等待“;异步超级()构造函数?,javascript,node.js,class,constructor,async-await,Javascript,Node.js,Class,Constructor,Async Await,我正在尝试从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 Prom

我正在尝试从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类中有一个方法(setapikes),它向PayPal发送生成mi访问令牌的请求,如果我放入
console.log(this.access\u token)
我正在获取我的访问令牌,但只有当我将它放入setapikes方法中时才会发生(我在这里省略了这个类的一些方法)

如果我把
console.log($paypal\u gateway.access\u token)
放进去,我就没有定义,这是显而易见的,因为paypal类构造函数正在返回一个承诺,但是在客户类构造函数中,我只是调用
super()
方法,没有异步方式,我试图把“async”放在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\u token)
,我也会得到未定义的,所以我不知道如何等待这个super()构造函数,你能帮我吗?

构造函数必须返回一个对象,特别是它定义的类的实例。它不能返回承诺,异步函数就是这样做的。您必须执行一个设置步骤。您可以创建一个异步工厂函数,该函数实例化对象并执行所有设置步骤,然后返回结果对象

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

}

我在@sdgluck comment的帮助下解决了这个问题,我避免了构造函数方法,并实现了一个异步初始化方法:

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

const axios=require(“axios”);
/**PayPal主类,该类将在实例出现时设置PayPal凭据*/
类贝宝{
setupEnvironment=async()=>{
//设置发送请求的基本URL
this.setAPIDomain();
//设置PayPal端点
此参数为.setPayPalEndpoints();
//设置API键
等待此消息;
}
setapikees=async()=>{
const paypal_credentials=this.getPayPalCredetials();
const{client\u id,client\u secret}=paypal\u凭证;
试一试{
常数响应=等待axios({
方法:“张贴”,
url:this.endpoints.get_access_令牌,
数据:“授予\类型=客户\凭证”,
标题:{
“接受语言”:“en_US”,
“接受”:“应用程序/json”
},
认证:{
用户名:客户端id,
密码:client_secret
},
});
this.access\u token=response.data.access\u token;
}捕获(错误){
console.log(error.response.data);
抛出新错误(Error.response.data.Error\u description);
}
}
}
类Customer扩展了PayPal(){
异步初始化=()=>{
等待此消息。setupEnvironment();
//更多初始化代码
}
}
const paypal_gateway=新客户();

等待paypal_gateway.init();//构造函数没有人返回值。你可以创建一个方法,然后等待这个方法。就个人而言,我不会在构造函数中使用异步代码-只要把它移到一个方法中,例如
init()
,然后等待它。你可以使用
super()。然后(()=>/*你的代码在这里*/)
从构造函数返回不是一个好主意,…例如
var c=new Customer()
c不会是Customer的实例,。。。一种常见的方法是,创建某种init函数。这是否回答了您的问题?没错,但问题是我必须实例Customer类,而不是PayPal类,但它给了我一个想法如果Customer类扩展了PayPal,那么它也将有setupEnvironment方法,并且它应该没有真正的区别
createPaypal
函数硬编码
PayPal
实例的使用。如果您在
PayPal
类上创建一个静态方法,那么这将更加动态
static async create(…args){const paypal=new this(…args);wait paypal.setupEnvironment();return paypal;}
此静态方法也可用于扩展
paypal
的类。例如,
const customer=customer.create()
,由于动态
newthis(…)
调用,它创建了
customer
类的实例。其中
指的是类。