Nodejs: доступ к "this" в асинхронной функции в методе класса - PullRequest
0 голосов
/ 28 мая 2018

У меня проблемы с доступом к "this" в методе, в котором я вызываю асинхронную функцию (поиск в базе данных).

В моем методе "getAll": я могу получить доступ к this._persons извне«PersonModel.find», но внутри функции обратного вызова «PersonModel.find» я не могу получить доступ к this._persons.

Я уже пытался добавить «PersonModel.find.bind (this)», но результатом былото же самое ...

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);
});

Как я могу получить доступ к this._persons в моей функции PersonModel.find?(Или мне нужно изменить мой код?

1 Ответ

0 голосов
/ 28 мая 2018

Использование => функция

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);
    });
}
...