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
2
Answers
getReferenceNumber
is notasync
, and does not return a promise. The onlyreturn
statement is in a nested function, which returns from that function, and not fromgetReferenceNumber
. Which meansgetReferenceNumber
returns no value, which is why you get `undefined.You probably want
fsPromises.readFile
instead.I believe this is equivalent.
You can swap
readFile
forreadFileSync
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.