-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
  • 705,106
  • 160
  • 1,004
  • 1,072
Alexander Beninski
  • 737
  • 1
  • 10
  • 23

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
  • 158,961
  • 49
  • 244
  • 292