【问题标题】:Cant access Instance Variables Inside Typescript Methods | It says the variable is unreachable无法访问 Typescript 方法中的实例变量 |它说变量无法访问
【发布时间】:2021-09-22 01:04:03
【问题描述】:
class User {
    public pname: string;
    private ptoken: string;
    public token_status:boolean = false;

  

    public constructor(pname: string, ptoken: string) {
        this.pname = pname;
        this.ptoken = ptoken;
    }




    public Token_Valid() : Promise<token_format>{

        
        return new Promise((accept:any)=>{

            db.all("select * from `token` where `name` = $name and `token` = $token;",{$name:this.pname,$token:this.ptoken},(err:any,res:any)=>{
                if(res[0]){
                    accept(res[0]);
                }else{
                    accept({Error:'Person was not found, or token is incorrect soryy ...'})
                }
            });

            
        })

      
        this.token_status = true;

       

    }

当我尝试在方法中分配布尔值时,会给出以下消息

** 有人可以解释错误发生的原因以及全局变量如何在 Typescript / Javascript 中的类中工作,就像在其他语言中一样,这不会是一个问题

【问题讨论】:

    标签: typescript class scope instance-variables unreachable-code


    【解决方案1】:

    这里的问题似乎很简单,你在Token_Valid()方法中返回了一个new Promise,但是在你返回它之后设置this.token_status

    在 JavaScript 中,在方法 * 的 return 语句之后什么都不能做,因此您需要将该方法重构为:

    1. 在您返回承诺之前设置变量
    2. 通过等待将promise的值保存为变量,然后设置this.token_status,返回之前保存的值。
    3. .then() 添加到返回的promise 中,该promise 接收一个值(从创建的promise 返回的值),该值改变this.token_status 的值,然后返回它接收的值。

    *除非你使用try { ... } finally { ... } 块。

    【讨论】:

    • 感谢克里斯的帮助和解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多