【发布时间】:2019-03-31 14:34:10
【问题描述】:
我有以下代码,我想做的是从数据库中获取一些数据(这似乎是成功的,我试图记录它),然后排列这些数据并发送一个数组作为响应。我的班级:
export class Controller {
currentQuestions: IQuestionArranged[] = []; // This should be my array that I am trying to send as response
constructor(){ }
public async startNewGame(req: express.Request, res: express.Response): Promise<void> {
let factory: RepositoryFactory = new RepositoryFactory();
let repository: RepositoryInterface = factory.createRepository();
let questionsFetched: IQuestionFetched[] = await repository.fetchQuestions(); // array of questions as they were fetched
// let currentQuestions: IQuestionArranged[] = []; // <<<<<
// forEach through fetched questions to arrange them
questionsFetched.forEach(currentQuestion => {
// check if the current question already exists in the array
if (this.currentQuestions.filter(e => e.id == currentQuestion.questionId).length != 0) {
// if yes -> find the question and add the new answer with its id
this.currentQuestions
.filter(e => e.id == currentQuestion.questionId)
.map(e => e.answers.push({
id: currentQuestion.answerId,
answer: currentQuestion.answer
}));
} else {
// if no -> add the new question with the new answer
this.currentQuestions.push({
id: currentQuestion.questionId,
question: currentQuestion.question,
answers: [{
id: currentQuestion.answerId,
answer: currentQuestion.answer
}]
});
}
});
res.send(this.currentQuestions);
}
}
但是我收到了这个错误,上面写着“UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'currentQuestions' of undefined”(完整的错误描述 here)。如果我使用局部变量(标有 5 个左箭头作为注释的变量)而不是类属性,它似乎工作得很好,这让我觉得我没有正确使用它,但我不知道我的错误在哪里...
【问题讨论】:
-
您正在寻求调试帮助,即not a proper problem statement。要回答您的隐含问题,您可以通过将您的上下文(即调用
startNewGame的Controller实例)作为第二个参数 (see here) 来修复Array.forEach中的this。
标签: javascript typescript express oop