gpt4 book ai didi

javascript - 位于 for-each 中的记录器的引用错误

转载 作者:行者123 更新时间:2023-12-01 00:41:53 29 4
gpt4 key购买 nike

我正在使用 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
};

我目前在 for-each 循环内的 logger 实例上遇到错误。

为什么我无法使用 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
};

关于javascript - 位于 for-each 中的记录器的引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57660005/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com