的Javascript通过这个和其他参数去发挥作用

问题描述 投票:0回答:1

我有了一个服务器对象的一个​​节点应用。该目的的功能连接()。它应该返回一个布尔值,并存储在该对象的连接。我可以得到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';

        }).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而这功能。如果你碰巧知道一个链接,可以帮助我理解这一点,我会很感激。

javascript asynchronous this
1个回答
1
投票

传递给this匿名函数内.then()是全球范围内。您可以使用箭头功能来保存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))
© www.soinside.com 2019 - 2024. All rights reserved.