-2

I was trying to read a JSON file using Async/Await, I created my example based Native async/await approach, and I got this error.

SyntaxError: await is only valid in async function

Here is my code.

const fs = require('fs-extra');
const xml2js = require('xml2js');  
const parser = new xml2js.Parser();

const path = "file.json";

function parseJM() {
return new Promise(function (resolve, reject) {
    fs.readFile(path, { encoding: 'utf-8'}, (err, data) => {
        if (err) { reject(err); }
        else {
            resolve (parser.parseString(data.replace(/<ent_seq>[0-9]*<\/ent_seq>/g, "")
             .replace(/&(?!(?:apos|quot|[gl]t|amp);|#)/g, '')));
        }
    });
});
}

const var1 = await parseJM();
console.log(var1);

What is wrong with my code? My node version is 11.9.0, my npm version is 6.7.0 and i am using Arch Linux.

Kaan Taha Köken
  • 933
  • 3
  • 17
  • 37

2 Answers2

3

You need to call await inside an async function.

(async () => {
    try {
        const var1 = await parseJM();
        console.log(var1);
    } catch (e) {
        console.error(e.message);
    }
})();

Edit: As suggested by @Nik Kyriakides

Shubham
  • 1,755
  • 3
  • 17
  • 33
2

The error itself is telling you exactly what the issue is. You can only await inside an async-marked function.

If that's your top-level code you can just use an async IIFE:

;(async () => {
  try {
    await doSomething()  
  } catch (err) {
    console.error(err)
  }
})()

or just then/catch it. async functions return a Promise after all:

doSomething() 
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.error(err)
  })
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167