【问题标题】:this.* not working with async/await javascript (node 8.6.0) [duplicate]this.* 不适用于 async/await javascript(节点 8.6.0)[重复]
【发布时间】:2018-03-12 18:13:43
【问题描述】:

我找不到这个错误的原因:

这是我的代码:

  create: async (data) => {
    const insertedData = await dbProvider.query('INSERT INTO users SET ?', data);
    console.log(this);
    return await this.getById(insertedData.insertId);
  },
  getById: async (id) => {
    const data = await dbProvider.query('SELECT * From users WHERE id = ?', id);
    return data;
  },

Create 被调用 await repo.create(data); create 调用 this.getById 导致错误。 知道为什么会这样吗?

【问题讨论】:

  • 这与async/await语法无关。

标签: node.js async-await ecmascript-2017


【解决方案1】:

因为箭头函数预先绑定到词法this

如果你想要一个动态的this 在函数内部,它不能是箭头函数:

  async create(data) {
    const insertedData = await dbProvider.query('INSERT INTO users SET ?', data);
    console.log(this);
    return await this.getById(insertedData.insertId);
  },
  async getById(id) {
    const data = await dbProvider.query('SELECT * From users WHERE id = ?', id);
    return data;
  },

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 2019-10-24
    • 2018-07-10
    • 2021-09-27
    • 1970-01-01
    • 2021-06-18
    • 2019-05-30
    相关资源
    最近更新 更多