The “unexpected reserved word (await)” error occurs in JavaScript when you use the await
keyword in a function that is not specified as async. To fix it, add an async
modifier to the function to mark it as async.
Here’s an example of the error occurring:
function getName() {
// ❌ SyntaxError: Unexpected reserved word
const str = await Promise.resolve('Coding Beauty');
return str;
}
Note: As this is a syntax error, the function doesn’t need to be invoked for it to be detected, and no part of the code runs until it is resolved.
The async
and await
keywords work together in JavaScript (hence the commonly used term, async/await
); to use the await
keyword in a function, you must add the async
modifier to the function to specify that it is an async function.
// ✅ Use "async" keyword modifier
async function getName() {
// ✅ Successful assignment - no error
const str = await Promise.resolve('Coding Beauty');
return str;
}
Fix “Unexpected reserved word (await)” error in nested function
If you’re using the await
keyword, it’s likely that you already know that it has to be in an async
function. What probably happened is that you nested functions and mistakenly ommited the async
modifier from the innermost function containing the await
keyword.
For example:
// ❌ SyntaxError: Unexpected reserved word
export const createTask =
async ({ description }) =>
// ❌ "async" keyword missing from innermost function
(dispatch) => {
await fetch('https://example.com/tasks', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ description }),
});
dispatch({ type: 'taskCreated', description });
};
For await
to work, the deepest function in the nesting hierarchy is required to be specified as async. It won’t work even if any or all of the outer functions are marked as async.
So we resolve the error in this case by adding the async
modifier to the innermost function:
// ✅ No error
export const createTask =
async ({ description }) =>
// ✅ Innermost function marked as async
async (dispatch) => {
await fetch('https://example.com/tasks', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ description }),
});
dispatch({ type: 'taskCreated', description });
};
In this example, we should be able to remove the async
keyword from the outer function, as it isn’t performing any asynchronous operations with await
, but this depends on whether the caller of createTask()
is expecting it to return a Promise
or not.
Here’s another example where this mistake frequently happens; using await
in an array looping method:
// ❌ SyntaxError: Unexpected reserved word
async function processPhotos(photoIds) {
const data = await Promise.all(photoIds.map((photoId) => {
const res = await fetch(`http://example.com/photos/${photoId}`);
return await res.json();
}));
// process data...
}
Like in the previous example, the error occurs because the async
keyword modifier is absent from the map()
callback, even though it’s present in the function that calls map()
. The fix is the same, add async
to the map()
callback.
// ✅ No error
async function processPhotos(photoIds) {
const data = await Promise.all(
photoIds.map(async (photoId) => {
const res = await fetch(`http://example.com/photos/${photoId}`);
return await res.json();
})
);
// processing...
}
Use await
at top level
If you’re trying to use await
at the top level of your file, you’ll need to set the type
attribute to "module"
in the script
tag referencing the file in the HTML. This works when your code runs in browser environments.
For example:
<script type="module" src="index.js"></script>
Now you’ll be able to use await
at the global scope in your file, e.g.:
console.log(await Promise.resolve('Coding Beauty'));
If you’re using Node.js, you’ll need to set the type
attribute to "module"
in your package.json
file.
{
"name": "cb-js",
"type": "module",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
// other fields...
}
If there’s no package.json
in your project directory, you can create one with the following command
# NPM
npm init -y
# Yarn
yarn init -y
The await
keyword will now work at the top level of your project files.