How to Fix unexpected reserved word ‘await’ in JavaScript

To fix the unexpected reserved word ‘await’ error, declare your function “async”.

The error unexpected reserved word await occurs when we use the ‘await’ keyword inside a not marked as async function. If we need to use the ‘await’, we should make the function ‘async’.

function getString() { // not marked as async function
  
  // unexpected reserved word 'await'
  const str = await Promise.resolve('Hello world!');
  return str;
}

// unexpected reserved word 'await'
const res = await Promise.resolve(42);
console.log(res)

Output

file:///Users/krunallathiya/Desktop/Code/R/app.js:3
 const str = await Promise.resolve('Hello world!');
 ^^^^^
SyntaxError: Unexpected reserved word

In this example, we didn’t mark the function as async so that this code will generate an “unexpected reserved word await” error.

To fix this error, declare your function as async.

async function getString() { // not marked as async function
 // unexpected reserved word 'await'
 const str = await Promise.resolve('Hello world!');
 return str;
}

//unexpected reserved word 'await'
const res = await Promise.resolve(42);
console.log(res)

Output

42

This code will run properly with no errors. However, if you use Node.js and want to use the await keyword on the top level, set the type attribute to the module on your package.json file.

See the below package.json file. This is a strict requirement if you use Node.js.

{
    "type": "module"
}

Set the attribute in your script tag to use it on the browser.

Use this tag on your HTML file.

<script type="module" src="app.js"></script>

Now you can use the top-level await keyword on your code. For browser:

console.log(await Promise.resolve(20));

That’s it.