简体   繁体   English

如何在自己的 class 中调用 new object 中的构造函数 function

[英]How to call constructor function inside new object in its own class

When I try to call this.logger.error() inside new Promise it won't work.How can I call this.logger.error() inside the new Promise .当我尝试在new Promise中调用this.logger.error()时,它不起作用。我如何在new Promise中调用this.logger.error() As of my knowledge this refers to the outside class, how to call the logger inside Promise object.据我所知, this指的是外部class,如何在内部调用logger Promise object。

export class MyClass {
    constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) {}


    async uploadfile(buffer, key: string): Promise<string> {
            const params = {
                Body: buffer,
                Bucket: 's3Bucket',
                Key: key,
                ContentType: 'application/pdf',
                ACL: 'public-read',
            };
            const path: string = await new Promise((resolve, reject) => {
                s3.upload(params, function(err, data) {
                    if (err) {
                        this.logger.error('Error',err)
                        reject('Error occurred');
                    }
                    return resolve(data.Location);
                });
            });

            return path;

    }
}

The keyword this will only bind the scope which it is called.关键字this只会绑定它所调用的 scope。 Calling it directly in a function that is not a class member/instance will bind to the function scope. You can assign this to a variable and use the variable inside your Promise在不是 class 成员/实例的 function 中直接调用它会绑定到 function scope。您可以将this分配给变量并使用 Promise 中的变量

class Example {

instanceFunction(){
  const thisReference = this
  return new Promise((accept)=>{
  accept(thisReference)
})

}

Above is example of how you would do it以上是您将如何做的示例

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

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