electron 在nodejs/sqlite3中,run的第一个回调参数返回类示例,我如何修复它?

at0kjp5o  于 5个月前  发布在  Electron
关注(0)|答案(1)|浏览(71)

我在TypeScript中有以下类:

class Log
{
    public id: number;
    public text: string;

    construct(text: string){
        this.text = text;
    }

    save(){
        db.run(
            `insert into logs(text) values (?) `,
            this.text,
            ((this: RunResult, err: Error | null) => {
                if(err){
                    //...
                }
                console.log(this);//expecting RunResult{} but Log{}
            })
        )
    }
}

字符串
我想在回调函数块中使用RunResult.lastID来更新日志示例的id,@types/sqlite3/index.d.ts包含以下声明:

run(params: any, callback?: (this: RunResult, err: Error | null) => void): this;


但是,回调参数中的this是Log类型,而不是RunResult类型。
如何获取正确的RunResult示例?this.lastID需要一个值,而不是undefined

ny6fqffe

ny6fqffe1#

run函数parameters中的this关键字不是要传递的参数,但它是函数上下文。此外,arrow函数没有上下文,因此回调函数中的this关键字引用Log类是正确的。
因此,首先,您必须在回调之外保留Log类上下文,并使用普通函数作为回调,而不是箭头函数。
下面是修改后的save函数:

save() {
    const instance = this;
    db.run(
        `insert into lorem(info) values (?) `,
        this.text,
        function (err: Error | null) {
        if (err) {
            console.log(err);
        }
        instance.id = this.lastID;
        console.log(this);
        }
    );
}

字符串

相关问题