javascript - 在另一个静态方法(JavaScript)中调用静态方法时,“this”关键字未定义
问题描述
我正在导出/导入一个空数组以实现 MVC 模式,并且我能够通过调用Mentor类的allMentors方法成功地将数据存储在其中。
其次,我想成为 DRY 并从数组中获取数据,然后用它来寻找特定的导师,但我得到一个空数组。
我搜索了互联网,并按照使用此关键字的示例并在另一个内部调用静态方法,但 NodeJS 抛出一个未定义的错误。
ALL MENTORS 方法
class Mentor{
static async allMentors(req, res) {
try {
users.forEach(user => {
if(user.is_mentor === true) {
mentors.push(user);
}
})
const ObjKeyRename = (src, map) => {
const dst = {};
for (const key in src) {
if (key in map)
// rename key
dst[map[key]] = src[key];
else
// same key
dst[key] = src[key];
}
return dst;
};
const uniqueMentors = Array.from(new Set(mentors.map(m => m.id)))
.map(id => {
return new Promise((resolve, reject)=> {
const currMentor = mentors.find(m => m.id === id);
const modMentor = ObjKeyRename(currMentor, { "id": "mentorId" });
return resolve(modMentor);
})
})
Promise.all(uniqueMentors).then(output => {
output.forEach(async obj => {
await delete obj['password'];
})
return res
.status(200)
.json(new ResponseHandler(200, 'All Mentors', output, null).result());
})
} catch (err) {
return res
.status(500)
.json(new ResponseHandler(500, err.message, null).result());
}
}
static async singleMentor(req, res) {
const returnedMentors = this.allMentors;
console.log('THE RETURNED:',returnedMentors)
const theMentor = returnedMentors.find(u => u.mentorId === parseInt(req.params.mentorId));
try {
if (!theMentor) return res
.status(404)
.json(new ResponseHandler(404, `Mentor number ${req.params.mentorId} not found`, null).result());
return res
.status(200)
.json(new ResponseHandler(200, 'Your mentor', theMentor, null).result());
} catch (err) {
return res
.status(500)
.json(new ResponseHandler(500, err.message, null).result())
}
}
}
export default Mentor;
我究竟做错了什么?感谢您作为 JS 学习者的持续帮助。
解决方案
您的代码存在多个问题:
- 静态方法需要由 Class(
Mentor
) 而不是 Reference(this
)调用 - 需要等待或使用回调(
.then()
)调用异步方法
因此,例如,您有课程MentorHandler
:
class Mentor {
constructor() {
}
static async singleMentor(req, res) {
// ... some more code
}
static async allMentors(req, res) {
// await the result of the method
// call by class
const returnedMentors = await Mentor.allMentors();
// ... some more code
}
}
推荐阅读
- qt - 使用 Qt 设置网格间距
- android - 扩展 UnityPlayerActivity 类时仅使用 onCreate 方法
- angular - 如何在 keyPress 事件上更改 ionic alertController 中的输入值
- laravel - api中间件在laravel中的作用是什么
- python - Gunicorn 无法找到 URL
- android - 如何在flutter中使用本机代码而不进行通道?
- animation - 斯威夫特用户界面。TabView 动画与选项卡上的 ScrollView
- image - 为什么在 laravel 上上传图像后我无法在 ckeditor 上编辑图像属性
- elasticsearch - Elasticsearch grok 模式在哪里定义?
- angular - 如何获取应用了“必需”验证的表单字段列表?