我有一个带有服务器对象的节点应用程序。该对象具有 connect() 函数。它应该返回一个 bool 值并将连接存储在对象的 this 中。 我要么得到这个骗局,要么得到这个。
this 未定义的函数示例:
return this.mysql.createConnection({
host: this.env.host,
user: this.env.user,
password: this.env.password,
database: this.env.database
}).then( (function(con){
this.connection = con;
return con.state === 'authenticated';
}).apply(this, [con])).catch(function (err) {
console.log(err);
return false;
});
con 未定义的函数示例:
return this.mysql.createConnection({
host: this.env.host,
user: this.env.user,
password: this.env.password,
database: this.env.database
}).then(function(con){
this.connection = con;
return con.state === 'authenticated';
}).catch(function (err) {
console.log(err);
return false;
});
我想保护 this.connection 中的 con ,我的问题是我无法同时在函数中获取 con 和 this 。 如果您碰巧知道一个可以帮助我理解这一点的链接,我将不胜感激。
最佳答案
传递给 .then()
的匿名函数中的
this
是全局范围。您可以使用箭头函数来保留 this
。
const o = class {
constructor() {
this.n = 0;
}
createConnection() {
// this within arrow function references the curren `class`
return Promise.resolve(this.state()).then(state => this.n = state + 1).then(state => console.log(this.state()))
}
state() {
return this.n;
}
}
let x = new o();
x.createConnection();
不确定什么
.apply(this, [con]))
旨在实现所使用的匿名函数。
另一种方法可能是使用名称定义函数并使用Function.protototype.bind()
function handlePromise(data) {
console.log(data, this)
}
const o = {abc:123}
Promise.resolve({def:456})
.then(handlePromise.bind(o))
关于Javascript 将这个参数和其他参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54610513/