Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Noah Silliman
The "unexpected reserved word await" error occurs when the await
keyword is
used inside of a function that was not marked as async
. To use the await
keyword inside of a function, mark the directly enclosing function as async
.
Here are 2 examples of how the error occurs.
function getString() { // 👈️ not marked async // ⛔️ unexpected reserved word 'await' const str = await Promise.resolve('hello'); return str; } // ⛔️ unexpected reserved word 'await' const result = await Promise.resolve(42); // 👈️ top-level await
Because we didn't declare the getString
function as async
we are not able to
use the await
keyword in it. Instead we should set the function as async
.
async function getString() { const str = await Promise.resolve('hello'); return str; }
A very common cause of the error is forgetting to set an inner function as
async, e.g. the ones we pass to methods like forEach
, map
, etc.
Keep in mind that the directly enclosing function has to be marked as async
for you to be able to use the await
keyword.
async function loopThrough() { ['a', 'b', 'c'].forEach(str => { // ⛔️ unexpected reserved word 'await' await Promise.resolve(str); }); }
We marked the loopThrough
function as async
, however we're using the await
keyword inside of the function we passed to the forEach
method.
Instead, we should have made the function we passed to forEach
async.
function loopThrough() { ['a', 'b', 'c'].forEach(async str => { await Promise.resolve(str); }); }
We declared the function we passed to the forEach
method as async, therefore
we are able to use the await
keyword in it.
async
for us to be able to use the await
keyword.If you're trying to use the await keyword on the top level, make sure you set
the type
attribute to module
in your package.json
file if you're using
node.js
or set the attribute in a script tag on the browser.
If you're on the browser, set the type
attribute to module
in your script
tag to be able to use top level await
.
<script type="module" src="index.js"></script>
Now you can use top level await in your code, e.g.
console.log(await Promise.resolve(10));
And here's how to use top level await
in Node.js.
Create package.json
file if you don't have one already:
npm init -y
Add the type
property and set it to module
in your package.json
file.
{ "type": "module", "name": "javascript", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
Now you can use top level await
in your Node.js code.