У меня проблемы с доступом к "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?(Или мне нужно изменить мой код?