javascript - 位于 for-each 中的记录器的参考错误
问题描述
我正在使用 javascript 并具有以下类:
const Product = require('../models').Product
class ProductService {
constructor(log) {
this.logger = log
}
async generateIssuerRatingChangeContent(id, helperService, productService) {
let products
try {
products = await productService.getproductByid(id)
} catch (error) {
this.logger.error(error)
}
this.logger.info("Get #products: " + products.length)
let contentArr = []
this.logger.info("##############Start to clean products##############")
products.forEach(async function (item) {
const res = {
//...
}
let resultString = await helperService.stringCleaner(res)
contentArr.push(resultString)
this.logger.info(resultString); // <--- HERE I get an ReferenceError!!!
console.log(resultString);
this.logger.info("#####################-DONE WITH " + item.id + "-#####################");
});
await helperService.writeContentToFile(contentArr)
}
}
module.exports = {
ProductService
};
我目前收到logger
位于 for-each 循环内的实例的错误。
为什么我不能访问它this
?
感谢您的回复!
解决方案
当您使用function
关键字定义回调时,上下文会发生变化。相反,请尝试使用将继承父上下文 ( this
) 的箭头函数。
const Product = require('../models').Product
class ProductService {
constructor(log) {
this.logger = log
}
async generateIssuerRatingChangeContent(id, helperService, productService) {
let products
try {
products = await productService.getproductByid(id)
} catch (error) {
this.logger.error(error)
}
this.logger.info("Get #products: " + products.length)
let contentArr = []
this.logger.info("##############Start to clean products##############")
products.forEach(async (item) => {
const res = {
//...
}
let resultString = await helperService.stringCleaner(res)
contentArr.push(resultString)
this.logger.info(resultString); // <--- HERE I get an ReferenceError!!!
console.log(resultString);
this.logger.info("#####################-DONE WITH " + item.id + "-#####################");
});
await helperService.writeContentToFile(contentArr)
}
}
module.exports = {
ProductService
};
推荐阅读
- php - php 转发请求,包括发布数据和上传的文件
- java - println() 和 printl("") 的区别
- reactjs - yield take() 后如何执行
- java - 字符或符号不能用 java 语言中的 char 数据类型表示
- javascript - 如何将折线图与 Excel 等原始数据表结合起来
- javascript - 如何在 VS Code 中启用 TabNine 语义完成?
- python - 如何从接收到的字节中显示或打印特定部分
- node.js - 为什么在简单的 Node.js 应用程序中无法识别我的模块?错误:找不到模块“fwsp-hydra-express”
- vue.js - 带有自定义按钮添加和删除的 Bootstrap Vue 表
- rust - 使用 Result::map 和 Box 时无法推断类型