首页 > 解决方案 > 位于 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

感谢您的回复!

标签: javascript

解决方案


当您使用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
};

推荐阅读