-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

1
  • 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, 2019 at 16:36

2 Answers 2

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');
} 
0
-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
})()
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.