-4

I am trying to write a simple node.js program that will take in a json5 file and convert it to a json file. I have found this https://www.npmjs.com/package/any-json which I believe will be useful.

This is the code I currently have...

const anyJson = require("any-json");

const str = await anyJson.encode({/* test comment */ "foo": "bar"}, 'json');

however it gives me this error...

const str = await anyJson.encode({/* test comment */ "foo": "bar"}, 'json'); 

(^^^^^ under the await)

SyntaxError: await is only valid in async function

Note: This exact code works in the npm runkit

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
begprog
  • 271
  • 1
  • 2
  • 8
  • If you specify the json file value... there's not waiting time... you should use await if you are calling an api or something that will eventually return a value.... – Gi1ber7 Feb 21 '19 at 16:36

2 Answers2

0

Well error is pretty self explanatory. For await to work, it should be within async function.

// as you can see await is valid only inside async
async function test() {
   const result = await myfunction()
}

const myfunction = async function(x, y) {
    return anyJson.encode({/* test comment */ "foo": "bar"}, 'json');
} 
kanhai shah
  • 1,193
  • 10
  • 14
-2

Exactly as stated, an await is only valid within an asynchronous function.

If you want to use async/await for a simple program, you can try wrapping the code in an async block that is executed directly

const anyJson = require("any-json");

(async () => {
  const str = await anyJson.encode({/* test comment */ "foo": "bar"}, 'json');
  //rest of your code here
})()
Jonas D.
  • 361
  • 4
  • 18