-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.

6
  • 4
    What is wrong with my code? ---> await is only valid in async function, like you've already answered in your question Commented Feb 8, 2019 at 12:36
  • 2
    The error told you exactly what's wrong with your code. Commented Feb 8, 2019 at 12:36
  • 2
    Your using fs-extra here, so don't even bother using new Promise.. All fs methods return promises if the callback isn't passed. Commented Feb 8, 2019 at 12:42
  • The purpose of writing like this, the promise is not enough for by itself. Commented Feb 8, 2019 at 12:49
  • I do not understand why the heck this community so harsh on people Commented Feb 8, 2019 at 12:53

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

try/catch is a must when you do this. Otherwise you're setting yourself up for swallowed errors.
is it possible without using IFFE's
@KaanTahaKöken Yes, you can use a .then/resolve since async-marked functions return a Promise.
@NikKyriakides Not exactly swallowed. You will get "unhandledRejection" if an error is thrown inside parseJM() call.
@Aikei True, bad choice of words.
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)
  })

4 Comments

Why the ;? Is it a typo or a clever hack I didn't know about?
Just to make sure that you don't fall into this trap.
That's how code looks when you don't use semi-colons consistently. Not really my thing.
Apart from IIFE's I've never had to prefix anything with a ;. My take is that it's far better w/o them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.