0

Im using this function but the console prints before i get the value, does anyone know how to fix it? Thanks!

async function getContent(){
  // Load client secrets from a local file.
  let my_content;
  await fs.readFile('credentials.json', async (err, content) => {
    if (err) return console.log('Error loading client secret file:', err);
    my_content = await JSON.parse(content);
  });
  console.log(my_content);
}
pdro_99
  • 87
  • 1
  • 6
  • 1
    The `console.log()` will fire immediately, but the contents of the function only after the file has loaded. Please try a tutorial on async. – mousetail Sep 15 '21 at 13:34
  • If `.readFile()` returns a `Promise` then it won't use a callback. If it uses a callback then it won't return a `Promise` (hopefully) – Andreas Sep 15 '21 at 13:35
  • 1
    `JSON.parse()` is not asynchronous – Andreas Sep 15 '21 at 13:35
  • JSON:parse its not asyncronous but the console log prints undefined, so it executes before readFile's function ends, thats my problem – pdro_99 Sep 15 '21 at 13:40
  • `import { promises } from "fs"; const jsonString = await promises.readFile('credentials.json'); const my_content = JSON.parse(jsonString); console.log(my_content);`. Use `await` OR a callback function, not both at the same time – Jeremy Thille Sep 15 '21 at 13:44

0 Answers0