b_it_s
b_it_s

Reputation: 714

Nodejs: access "this" in async function in class method

I'm having trouble accessing "this" within a method in which I'm calling an async function (search in database).

In my "getAll" method: I can access this._persons outside of "PersonModel.find", but inside the callback of "PersonModel.find" I cannot access this._persons.

I already tried to add "PersonModel.find.bind(this)", but result was the same...

var PersonModel = require('./model')
//Class
class personRepository {
    constructor() {
        this._persons = new Set();
    }

    getAll( cb ) {
        let results = new Set();

        PersonModel.find({}, 'firstName lastName', function (err, people) {
            if (err) { 
                console.error(err);
                return next(err) 
            }
            people.forEach((person, index) => {
                results.add(person);
            });
            //this._persons.add("this._persons isn't accessible");
            //cb(this._persons);
        });
        this._persons.add("this._persons is accessible");
        console.log(this);
    }
}

// Test
var personRepo = new PersonRepository();
personRepo.getAll( (persons) => {
    for (let item of persons) console.log(item);
});

How can I access this._persons in my PersonModel.find function? (Or do I need to redesign my code?

Upvotes: 0

Views: 366

Answers (1)

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

Use => function

getAll( cb ) {
    let results = new Set();

    PersonModel.find({}, 'firstName lastName', (err, people) => {
        if (err) { 
            console.error(err);
            return next(err) 
        }
        people.forEach((person, index) => {
            results.add(person);
        });
        this._persons = results;

        cb(this._persons);
    });
}

Upvotes: 1

Related Questions