EZC404
EZC404

Reputation: 25

typescript function skips if statments

export function GetData(uuid: any): string {
  var dirPath: string = path.join(__dirname, "../Container/" + uuid);
  console.log(dirPath);
  if (fs.existsSync(dirPath) == true) {
    fs.readFile(dirPath, "utf8", (err: any, string: any) => {
      if (err) {
        console.log("ERROR: " + err);
        return "null1";
      } else {
        console.log("token: " + JSON.parse(string).token);
        return JSON.parse(string).token || "";
      }
    });
  } else {
    console.log("will send null");
    return "null2";
  }
  return "end";
}

I have no idea why it's happening and in the console I also gives out "token: " and the token part of the json but if i run it in as a function and console log the result it gives me "end"

Upvotes: 0

Views: 20

Answers (1)

Christian
Christian

Reputation: 22343

fs.readFile is an async function with returns a promise.

So the function returns before you get the token. That's why you get the end.

You could either use fs.readFileSync to make it synchronous or you could use async-await.

Upvotes: 1

Related Questions