3

I'm having trouble with async/await with Node. When I try this:

function Read_Json_File() {
   fs.readFile('import.json','utf-8',(err, data) => {  
       if (err) throw err;
       json_data = JSON.parse(data);

       return json_data;

   });
}

async function run_demo() {
    let get_json_file = await Read_Json_File();
    console.log(get_json_file);
}

run_demo();

It returns undefined instead of the JSON from the file. Why doesn't it wait for the file reading to finish?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

3 Answers3

4

You're not returning anything from Read_Json_File, thus you get undefined -- you're returning data from the callback which doesn't result in anything. Instead, to use async/await, you'd need to promisify fs.readFile since it's not already. Then you'll be able to use async/await:

function readJSONFile() {
  return new Promise((resolve, reject) => {
    fs.readFile('import.json', 'utf-8', (err, data) => { 
      if (err) reject(err);
      resolve(JSON.parse(data));
    });
  });
}

Await requires an actual promise to wait for. What this does is return a promise to use await on. Thus, we wait until we call resolve - which happens when we're done loading the JSON:

let json = await readJSONFile();
console.log(json);

Here we call readJSONFile. This returns a promise which resolves when the JSON file is done loading, and allows for seemingly synchronous execution of asynchronous code.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • yeah now it works like a dream thanks , but i heard i can use async/await without using Promise . is that true? –  Dec 13 '17 at 09:12
  • @OFSTTP Await *expects a promise*. Async/await is just syntactic sugar for promises. Once you boil it down, async/await is just promises -- you can't just execute async code synchronously. You will always have to use promises to some degree, and async/await functions eventually become more promises and thens. – Andrew Li Dec 13 '17 at 09:13
  • @OFSTTP See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await –  Dec 13 '17 at 09:14
0

You missed promise resolve and reject.

Use as below.

function Read_Json_File() {
    return new Promise((resolve,reject)=> {
           fs.readFile('import.json','utf-8',(err, data) => {  
               if (err) reject(err);
               json_data = JSON.parse(data);

               resolve(json_data);

           });
    }
});
sungyong
  • 2,267
  • 8
  • 38
  • 66
0

try it:

      function Read_Json_File() {
          return new Promise(resolve,reject => {
            fs.readFile('import.json','utf-8',(err, data) => {  
              if (err) reject(err);
                json_data = JSON.parse(data);

              resolve(json_data);
           });

   }
  • This is an exact copy of the two previous answers, this time with bad indentation and without any explanatory text. –  Dec 13 '17 at 09:12