0

I'm using NodeJS and MySQL with the following class setup. I am grabbing a row from DB and then am going to assign properties/values to object. My issue is I'm not sure how to bind the "this" from the Provider object to the query callback.

class Provider {
    constructor(id){
        if(id){
            this.load(id);
        }
    }

    load(id){
        db.query("SELECT * FROM providers WHERE provider_id = " + id, function(err, res){
            if (err) {
                console.log(err);
            } else {
                // Here I'd like to have this refer to Provider and not query function
                console.log(this);
            }
        });
    }
};

I have tried:

let getById = db.query.bind(this);

But that doesn't seem to do the trick...

nas7
  • 1
  • 1
  • You need to bind a callback to this, not db.query. Use an arrow. – Estus Flask Aug 27 '20 at 21:32
  • @EstusFlask How should I use an arrow function in this scenario? Would it be load = (id) => {} or inside the callback like (err, res) => {}? – nas7 Aug 27 '20 at 21:36
  • @EstusFlask That worked. Thank you so much! I usually avoid arrow functions because they're not as readable for me, but I won't make that mistake again. – nas7 Aug 27 '20 at 21:38
  • The 2nd should do the trick. Check the explanation in dupe question. Yes, the difference between regular and arrow functions is more than visual, they aren’t always interchangeable. – Estus Flask Aug 27 '20 at 21:40

0 Answers0