Leon Bartz
Leon Bartz

Reputation: 63

Javascript pass this and other param to function

I have a node application that has a server object. This object has the function connect(). It is supposed to return a boolean and store the connection in the this of the object. I can either get the con or the this.

Example of a function where this is not undefined:

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;

        });

Example of a function where con is not undefined:

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;

        });

I want to safe the con in this.connection my problem is I can't get con and this in the function at the same time. If you happen to know a link that can help me understand this I'd be grateful.

Upvotes: 0

Views: 56

Answers (1)

guest271314
guest271314

Reputation: 1

this within an anonymous function passed to .then() is the global scope. You can use arrow function to preserve 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();

Am not certain what

.apply(this, [con]))

is intended to achieve as to the anonymous functions used.

Another approach could be to define the function with a name and use Function.protototype.bind()

function handlePromise(data) {
  console.log(data, this)
}

const o = {abc:123}

Promise.resolve({def:456})
.then(handlePromise.bind(o))

Upvotes: 1

Related Questions