首页 > 解决方案 > 为什么我的变量没有在错误处理功能中更新?

问题描述

我在将某些内容写入文件时用于处理错误的函数中遇到了一些问题。在这个函数中,我想显示刚刚写入的文件名,但是,我的错误函数只显示最后一个文件名,而不显示其余文件名。为什么是这样?是范围问题吗?

我的代码

var myArray = ["A","B","C"]
// File variable
const fileHandler = require('fs');

for (let currentArrayElement in myArray ){

    hexFile = myArray[currentArrayElement];
        hexFile += ".hex"

        console.log("hexFile---->"+hexFile);
        // Writting serilaNumberInHex into a .hex file called hexFile
        fileHandler.writeFile(hexFile,"blabla" , function(err) {
            if(err) {
                return console.log(err);
            }
            console.log("[Info] File " + hexFile + " was succesfully created");
        }); 
}

输出

hexFile---->A.hex
hexFile---->B.hex
hexFile---->C.hex
[Info] File C.hex was succesfully created
[Info] File C.hex was succesfully created
[Info] File C.hex was succesfully created
[Finished in 0.2s]

预期产出

hexFile---->A.hex
hexFile---->B.hex
hexFile---->C.hex
[Info] File A.hex was succesfully created
[Info] File B.hex was succesfully created
[Info] File C.hex was succesfully created
[Finished in 0.2s]

[解决方案] 感谢杜尔加

我的代码

var myArray = ["A","B","C"]
// File variable
const fileHandler = require('fs');

for (let currentArrayElement in myArray ){

    let hexFile = myArray[currentArrayElement];
        hexFile += ".hex"

        console.log("hexFile---->"+hexFile);
        // Writting serilaNumberInHex into a .hex file called hexFile
        fileHandler.writeFile(hexFile,"blabla" , function(err) {
            if(err) {
                return console.log(err);
            }
            console.log("[Info] File " + hexFile + " was succesfully created");
        }); 
}

标签: javascriptnode.js

解决方案


推荐阅读