JSON读取函数返回Undefined而不是预期的值 – TypeScript

huangapple go评论73阅读模式
英文:

(Answered) JSON reading function returning Undefined instead of expected value - Typescript

问题

我正在编写一个函数,根据传递给它的内容来读取一个JSON文件并返回该值。在实际函数内部,我可以将结果输出到控制台,但当我返回它然后再输出到控制台时,我得到的是undefined。

我正在处理的JSON文件如下所示:

{
    "ECMadrid": "tbd",
    "ECParis": "tbd2"
}

我用来读取文件的函数如下所示:

getReferenceNumber(productName){
    fs.readFile('./filepath.json', 'utf-8', (err, jsonString) => {
        if (err) {
            console.log(err)
        } else {
            try {
                const data = JSON.parse(jsonString);
                console.log("The reference number before returning is: ", data[productName]);
                return data[productName];
            } catch (err) {
                console.log("Error parsing JSON:", err);
            }
        }
    });
} 

我在测试文件中像这样调用该函数:

let referenceNumber = await jsonHelper.getReferenceNumber("ECMadrid");
await console.log("I got sent: ", referenceNumber);

我期望这两个控制台输出都输出相同的结果,但实际上我的输出是这样的(值得注意的是,它首先输出函数调用后的控制台日志,我认为这很奇怪,值得指出):

I got sent: undefined
The reference number before returning is: tbd

我正在尝试弄清楚为什么getReferenceNumber函数正确地将我想要的内容分配给data[productName],但在实际调用它的类中返回undefined。提前感谢您的任何反馈。

编辑:回答得很正确和迅速,谢谢!

英文:

I am working on a function to read a JSON file based on what is past to it and return the value. Inside the actual function, I can output to the console exactly what I expect, but when I return it then output to the console I get undefined instead.

The JSON file I'm working with looks like this:

{
    "ECMadrid": "tbd",
    "ECParis": "tbd2"
}

The function I use to read the file looks like this:

    getReferenceNumber(productName){
        fs.readFile('./filepath.json', 'utf-8', (err, jsonString) => {
            if (err) {
                console.log(err)
            } else {
                try {
                    const data = JSON.parse(jsonString);
                    console.log("The reference number before returning is: ", data[productName]);
                    return data[productName];
                } catch (err) {
                    console.log("Error parsing JSON:", err);
                }
            }
        });
    } 

And I call the function inside a test file like this:

let referenceNumber = await jsonHelper.getReferenceNumber("ECMadrid");
await console.log("I got sent: ", referenceNumber);

I would expect both of those console logs to output the same result but instead my output is like this (and notably, it outputs the console log that comes after the function call first, which I thought was strange and worth pointing out):

> I got sent: undefined
> The reference number before returning is: tbd

I'm trying to figure out why the getReferenceNumber function is correctly assigning what I want to data[productName] but returning undefined to the class where I'm actually calling it. Thanks in advance for any feedback

Edit: Answered correctly and quickly, thank you!

答案1

得分: 1

getReferenceNumber 不是 async,也不返回一个 promise。唯一的 return 语句在一个嵌套的函数中,它会从那个函数中返回,而不是从 getReferenceNumber 中返回。这意味着 getReferenceNumber 不返回任何值,这就是为什么你得到 undefined 的原因。

你可能想要使用 fsPromises.readFile 替代。

我认为这是等效的。

async getReferenceNumber(productName: string) {
  try {
    const jsonString = await fs.promises.readFile('./filepath.json', 'utf-8');

    try {
      const data = JSON.parse(jsonString);
      console.log("在返回之前的参考号是:", data[productName]);
      return data[productName];
    }
    catch (err) {
      console.log("解析 JSON 时出错:", err);
    }
  } catch (err) {
    console.log(err);
  }
}
英文:

getReferenceNumber is not async, and does not return a promise. The only return statement is in a nested function, which returns from that function, and not from getReferenceNumber. Which means getReferenceNumber returns no value, which is why you get `undefined.

You probably want fsPromises.readFile instead.

I believe this is equivalent.

async getReferenceNumber(productName: string) {
  try {
    const jsonString = await fs.promises.readFile('./filepath.json', 'utf-8')

    try {
      const data = JSON.parse(jsonString);
      console.log("The reference number before returning is: ", data[productName]);
      return data[productName];
    }
    catch (err) {
      console.log("Error parsing JSON:", err);
    }
  } catch (err) {
    console.log(err);
  }
}

答案2

得分: 1

你可以将readFile替换为readFileSync来使用同步调用(如果你可以接受它是阻塞代码的话)。
然后,你可以在测试文件中删除你的await

英文:

You can swap readFile for readFileSync to use a synchronous call (if you are okay with it being blocking code).
You can then remove your await's in your test file.

huangapple
  • 本文由 发表于 2023年7月11日 03:04:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76656616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定