-1

I couldn't find why I get this error:

enter image description here

And here is my code:

  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 gets called with await repo.create(data); the create calls this.getById which results in an error. Any idea why this happens?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Alexander Beninski
  • 817
  • 3
  • 11
  • 24

1 Answers1

2

Because arrow functions are pre-bound to the lexical this.

If you want a dynamic this inside of a function, it cannot be an arrow function:

  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;
  },
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308