Javascript 将这个参数和其他参数传递给函数

标签 javascript asynchronous this

我有一个带有服务器对象的节点应用程序。该对象具有 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/

相关文章:

java - 在JAVA中发出多个http请求的快速异步方法

node.js - 异步函数discord.js 中的awaitMessages

javascript - 访问图像元素的父对象属性

javascript - 购物车挑战 JavaScript 逻辑。有不止一种方法可以解决吗?

javascript - 单击后定义 'this'

javascript - 如何从响应式 Canvas 获取图像?

javascript - 移动设备上的 Jquery CSS 动画错误

javascript - YouTube 视频自动播放无法在 iPhone 设备的 Chrome 上运行

Javascript 使用 setInterval 减少值超时并清除它?

javascript - 将回调更改为 promise 链