Solution
Use the await
directly inside the scope you are using async
and remove the top scope async
as it’s redundant.
The correct way to write this:
const sendVerificationEmail = () =>
async (dispatch) => {
await Auth.sendEmailVerification();
// some code..
};
Elaboration
You had the error because you used the await
keyword without the async
directly in the scope with the await
, you had 2 functions there, one inside the other, you had async
on the top one but not on the inner one, where it matters.
Wrong way:
const sendVerificationEmail = async () =>
// notice that an async before the (dispatch) is missing
(dispatch) => {
await Auth.sendEmailVerification();
// some code..
};
From this, an error will be generated (the latest error available from Chrome):
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
Reference
Async Functions
An async function is a function declared with the async keyword, and
the await keyword is permitted within it. The async and await keywords
enable asynchronous, promise-based behavior to be written in a cleaner
style, avoiding the need to explicitly configure promise chains.
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.
Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.
@markbjerke
Node.js wrapper function that contains your module is not an async function (nor is it a generator). Identifier await
is parsed as a keyword only in async functions, while it can be a standard variable in non-async functions.
If you want to use await
as a keyword and don’t want to declare separate named async function just to execute it, you can define async IIFE and put your code in it, like this:
(async () => { try{ for await (let pkg of installPackages(items)) console.log(pkg); }catch(e){ console.log(e.stack); } })();
If you’re not sure whether something is a bug or not, I suggest posting in nodejs/help repo firstly next time.
The unexpected reserved word ‘await’ vueJS code exception affects your programming experience when you forget to declare async functions. Unfortunately, this leads to many obstacles because the unexpected reserved word fails to interpret the inputs and render the commands, forcing your system to display a warning.
Although the unexpected reserved word ‘await’ React Native error happens for many reasons, this in-depth guide covers the most sophisticated solutions that work for all instances and bugs.
In addition, we will help you recreate the reserved word code exception using real-life examples and scripts millions of developers use daily, especially with JS programs.
Contents
- Why Is the Unexpected Reserved Word ‘Await’ Bug Happening?
- – Awaiting for a Procedure Without Declaring the Function
- – Using the Package Manager on a Docker Environment
- How To Remove the Unexpected Reserved Word ‘Await’ Code Exception?
- – Adding an Asynchronous Property to the Inner Function
- Conclusion
Why Is the Unexpected Reserved Word ‘Await’ Bug Happening?
The unexpected reserved word ‘await’ Vite error nearly always happens when your document lacks adequate declarations for the async functions with the unexpected reserved word. Unfortunately, the same error occurs with other inputs, although it is the most typical with the awaited procedure.
Therefore, you will likely experience the unexpected reserved word ‘await’ lwc exception when you use the specific word in a function that is not declared async. Although this only sometimes happens to skillful developers and programmers, it can affect any program or document, especially those with complex inputs.
On the flip side, applying the debugging methods and solutions for the unexpected reserved word ‘await’ Jest test only takes a minute, as you will soon learn. The point worth noting is that troubleshooting the document and pinpointing the exact failed command with advanced programs is the most challenging step.
However, no need to worry as we will help you recreate the unexpected reserved word ‘await’ in React to learn more about the error’s dynamic properties. Luckily, the lack of correct async functions is this error’s most standard culprit, although it happens in most programming languages and programs.
Hence, we wrote two chapters recreating the unexpected reserved word ‘await’ Axios code exception using standard elements and properties. Still, it would help if you remained calm if your project’s data differs because each script and syntax is unique, launching various procedures and functions.
– Awaiting for a Procedure Without Declaring the Function
This guide’s first broken script attempts to await a procedure without declaring the async function. Although this procedure looks ordinary and only requires a few elements, your system throws the unexpected reserved word ‘await’ in useeffect code exception, indicating that there are failed inputs.
Hence, the example we will show you include a single async function and schema for accepting the data. So, we will provide the entire code snippet throwing the error and confirming the lack of functional declarations.
You can learn more about this script in the following example:
const uniques = [‘name’, ’email’];
return Promise.all (uniques.map (async (field) => {
const query = {};
query [field] = data [field];
query.deleted = false;
return model.findOne (query);
}));
}
schema.statics.create = async function create (data) {
try {
const results = await checkIfDatabaseHasUsersWithSameNameAndEmail (data);
results.forEach ((result) => {
console.log (`Here’s the issue: $ {JSON.stringify (result)} ` );
throw new Error (‘Do something about it.’);
});
const company = new this (data);
return company.save();
} catch (error) {
throw error;
}
};
As you can tell, this short script fails to render the values and launches an exception due to the lack of async functions.
In addition, the code snippet indicates something about the error, but providing the complete error log is more beneficial. However, we will not exemplify the stack trace in this section because we want to focus on a different application.
Namely, we will help you reproduce the error on a Docker environment on Mac OS and list the complete error log because it pinpoints the exact failed path.
– Using the Package Manager on a Docker Environment
This article’s second and last invalid instance uses the package manager on a Docker environment. As explained earlier, your system blocks the procedure due to a single code line in the main document setting the dependency. So, we will exemplify the script, system information, and entire broken stack trace.
The following example helps you learn more about the main script:
838 contributors
sapphi-red chore: node prefix lint (#67185) ✓
#!/usr/bin/env node
import performance } from ‘node: perf_he
if (!import.meta.url.includes (‘node_modules’)) {
}
try {
await import(‘source-map-support’).then((r) => r.default.install())
catch (e) {}
global._ vite_start_time = performance.now()
Although we could list other inputs and elements, we kept the syntax as short as possible. In addition, the following example helps you learn more about the system’s versions and binaries:
OS: macOS 12.5
CPU: (8) x64 Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
Memory: 51.91 MB / 16.00 GB
Shell: 5.8.2 – /bin/zsh
Binaries:
Node: 18.7.1 – ~/.nvm/versions/node/v18.7.0/bin/node
Yarn: 1.22.20 – ~/.nvm/versions/node/v18.7.0/bin/yarn
npm: 8.15.1 – ~/.nvm/versions/node/v18.7.0/bin/npm
Browsers:
Chrome: 115.0.57615.134
Safari: 15.6
So, the only thing left is exemplifying the invalid message. You can learn more about this in the following example:
file:///app/node_modules/vite/bin/vite.js:7
await import(‘source-map-support’).then((r) => r.default.install())
^^^^^
SyntaxError: Unexpected reserved word
at Loader.moduleStrategy (internal/modules/esm/translators.js:140:18)
at async link (internal/modules/esm/module_job.js:45:31)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! portal-ui@0.0.0 build:dev: vue-tsc –noEmit && vite build –mode develop
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the portal-ui@0.0.0 build:dev script.
npm ERR! /root/.npm/_logs/2022-12-12T10_43_04_971Z-debug.log
This example confirms the code’s inconsistencies and flaws with the synchronized functions. Luckily, you can quickly overcome them.
How To Remove the Unexpected Reserved Word ‘Await’ Code Exception?
You can remove the unexpected reserved word ‘await’ code exception by making the function enclosing the await property asynchronous.
Contrarily, you can remove the await command and reenable all procedures, but this changes your script completely. Hence, we suggest using the first method because it does not affect other operations.
So, you can get around this obstacle by changing the default sync property of your primary function. As a result, you will enable the await command and allow the snippet to render its values. Fortunately, we will exemplify the entire procedure by fixing the broken example from the first chapter.
The following example provides a fully functional document:
const deviceId = await AsyncStorage.getItem(‘@device_ID’)
const sessionId = await AsyncStorage.getItem(‘@session_Id’)
console.log (‘device ID: ‘,deviceId, ‘session ID: ‘, sessionId)
setRefreshing (true);
// wait (5000).then(() => setRefreshing (false));
(async () => {
try{
let ServiceTicketData = await fetch (`$ {API_URL} /v1/ serviceTicket`, {
method: ‘GET’,
headers: {
Accept: ‘application/ json’,
‘apiKey’: ‘aklse90234e’,
‘deviceId’: deviceId,
‘sessionId’: sessionId
},
});
let STData = await ServiceTicketData.json();
console.log (STData);
setRefreshing (false)
} catch (error) {
console.log (error);
}
})()
}, [refreshing]);
As explained, this syntax catches the error and reenables the processes by making the function async. As a result, you can complete the other failed inputs because this method flattens out all inconsistencies.
First, however, remember to apply this debugging approach to all code snippets containing the await command. Fortunately, this is relatively easy because the warning indicates the code exceptions.
– Adding an Asynchronous Property to the Inner Function
You can resolve your document by adding the async property directly to the inner function, serving the same purpose as before. Hence, the following example provides the broken script:
(dispatch) => {
try {
dispatch({ type: EMAIL_FETCHING, payload: true });
await Auth.sendEmailVerification();
dispatch({ type: EMAIL_FETCHING, payload: false }))
} catch (error) {
dispatch({ type: EMAIL_FETCHING, payload: false });
throw new Error(error);
}
};
Luckily, the fixed code is similar because a single property enables all procedures, as explained below:
async (dispatch) => {
try {
dispatch({ type: EMAIL_FETCHING, payload: true });
await Auth.sendEmailVerification();
dispatch({ type: EMAIL_FETCHING, payload: false }))
} catch (error) {
dispatch({ type: EMAIL_FETCHING, payload: false });
throw new Error(error);
}
};
This example completes our debugging guide using real-life examples and scripts.
Conclusion
The unexpected reserved word ‘await’ code exception affects your programming experience when you forget to declare async functions. Remember the following details before you fix the program:
- The lack of adequate properties in the primary function is this mistake’s only cause
- We recreated the code exception when awaiting a procedure without declaring the async function
- Making the function enclosing the await property asynchronous is the best debugging approach
- You can add the async property directly to the main function
The error should no longer ruin your application or project because you learned the most advanced debugging methods. Nevertheless, we encourage you to open your document, troubleshoot the script, and apply our debugging techniques.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
To fix the unexpected reserved word ‘await’ error in JavaScript, 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
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.
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.
Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit «Cookie Settings» to provide a controlled consent.
Overview
The unexpected reserved word await
error happens when you use the await
keyword in a function that is not marked with the async
keyword. The await
keyword is not allowed in non-async functions.
For example, this code will show the error unexpected reserved word await
:
// Define an async function
async function myFunction() {
console.log('Hello');
}
// Define a non-async function
function mySecondFunction() {
await myFunction();
}
When running the code, it will show the error unexpected reserved word await
because we used the await
keyword in the myFunction
function. The reason for this is that the await
keyword is not allowed in non-async functions. To fix this, we can add the async
keyword to the mySecondFunction
function.
async function mySecondFunction() {
await myFunction();
}
Use the async
/await
in arrow functions
It is possible to use the async
keyword in arrow functions.
const getUser = async () => {
return PPromise.resolve({
name: 'John'
});
};
const getServerProps = async () => {
const user = await getUser();
return {
user
};
};
If you have error in arrow function that says Unexpected reserved word await
, you can use the async
keyword as shown in the example above.
Summary
What is the difference between `async` and `await`?
async
is a keyword that is used to define a function that returns a promise. await
is a keyword that is used to wait for a promise to resolve.
What is the reason for the `unexpected reserved word await` error?
The unexpected reserved word await
error happens when you use the await
keyword in a function that is not marked with the async
keyword. The await
keyword is not allowed in non-async functions.
How can I fix the `unexpected reserved word await` error?
To fix the unexpected reserved word await
error, you can add the async
keyword to the function that you intend to use the await
keyword in.
Can I use the `await` keyword in arrow functions?
Yes, you can use the await
keyword in arrow functions.
Can I write an `async` function withouth the `await` keyword?
Yes, you can write an async
function withouth the await
keyword.
While are you want to use await keyword without async directly in the scope with the await, Then you will face Unexpected reserved word ‘await’, this error.
In this article, we will discuss about this Unexpected reserved word ‘await’ error in ReactJs. And how to resolve the error all the possible solutions with examples.
How Unexpected reserved word ‘await’ Error Occurs?
Most of the time you get this error when the await keyword is used inside of a function that was not marked as async.
Unexpected reserved word 'await'
How To Fix Unexpected reserved word ‘await’ Error?
There are different ways to fix Unexpected reserved word ‘await’ this error. Let us take a look at every solution.
How To Fix Unexpected reserved word ‘await’ Error?
To Solve Unexpected reserved word ‘await’ Error If you not declare your function as a async you can’t able to use await. So, you have to set your function as a async and then you use await. Now, your error will be solved.
Unexpected reserved word ‘await’
To Solve Unexpected reserved word ‘await’ Error If you not declare your function as a async you can’t able to use await. So, you have to set your function as a async and then you use await. Now, your error will be solved.
Solution 1: declare Async
If you not declare your function as a async you can’t able to use await keyword. So, you have to set your function as a async and then you use await.
async function getString() { // Declare async Here
const myData = await axios.get('my_api_call); // Now you can use Await
return myData;
}
Don’t forget that the directly enclosing function has to be marked as async for you able to use the await keyword.
async function loopThrough() {
['a', 'b', 'c'].forEach(str => {
// unexpected reserved word 'await'
await Promise.resolve(str);
});
}
Now, Your error will be solved.
Conclusion
In this article, we have discussed what causes the error and we have discussed ways to fix the error.
we hope this article has been informative. Thank you for reading. Kindly comment and let us know if you found it helpful.
;
Date: Sun Aug 07 2022
Tags:
Node.JS »»»» JavaScript
The error Unexpected Reserved Word usually means you’re using await in a non-async function. But what if Mocha throws this error, citing a test suite file that’s clean of such problems? To save spending fruitless hours, read this short article.
The error Unexpected Reserved Word means that the JavaScript compiler saw a reserved word, meaning a keyword special to the compiler, when it wasn’t expected. THe typical case is using await
in a function that hasn’t been marked async
.
In this case I found Mocha — a popular framework for writing unit tests — to incorrectly report which source file contained the unexpected reserved word. My test suite threw that error message, but Mocha identified the incorrect source file.
Usually a compiler, or a test framework, reporting a syntax error will tell us the actual line of code, and the offending code. But, in this case Mocha does not report the line number, nor the affected code, and to make it worse it reports the error as occuring in a different source file from its actual location.
Because Mocha incorrectly reported the location of the unexpected reserved word error, I spent fruitless hours double and triple checking the syntax of a source file which contained no such error.
Let’s start with the usual case:
$ cat unreserved.mjs
function a() {
await console.log(`This will throw an error`);
}
$ node unreserved.mjs
file:///home/david/Projects/akasharender/akasharender/test/unreserved.mjs:3
await console.log(`This will throw an error`);
^^^^^
SyntaxError: Unexpected reserved word
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)
at async link (node:internal/modules/esm/module_job:67:21)
This is what we normally see. We’ve created an ES6 module, unreserved.mjs
, containing a non-async function. Within that function is the await
keyword. That’s a use of a reserved word, await
, in the incorrect context. In this case the error report does an excellent job of letting us know what the problem is, and where it occurred.
This is the desired behavior, for the compiler to do a good job of letting us know what’s going on. We can go directly to the affected line of source code, and immediately know what to do, after groaning «Doh«.
Consider a real package, where an actual (and useful) module has been written, which contains that problem. Then, you go to write a test suite for this module, because you’re following good test-first-development practices.
$ cat test-unreserved.mjs
import * as unreserved from './unreserved.mjs';
$ npx mocha test-unreserved.mjs
SyntaxError[ @/home/david/Projects/akasharender/akasharender/test/test-unreserved.mjs ]: Unexpected reserved word
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)
Your test suite of course must import the application code to execute test cases. This means the unreserved.mjs
module. Because we just created that file, we can easily remember the error. In this case, Mocha doesn’t give us a clean error message. It simply says Unexpected reserved word, and further it identifies test-unreserved.mjs
as containing the problem.
Again, consider that this is instead happening in a real package. The test suite could have 1500 lines of code, and the module being tested has a similar amount of code.
Because Mocha positively identifies the test suite as containing the unexpected reserved word, it’s easy to then spend several hours combing through the test suite. You check every use of await
and it’s all correct. You check closely every loop, every function, every test case. You use VS Code and collapse every block, and because the editor correctly collapses each block, it seems the editor believes this is correctly constructed JavaScript. You then try commenting out all code, and still the error shows up. Finally you try commenting out the import
statements one by one, and voila the error goes away with one particular import
statement.
Checking inside that file you might then find a non-async function where the async
keyword was used. That’s easily fixed, and that particular error goes away. There may have been other problems, and you’ll know the original problem was fixed because the error message changes.
$ npx mocha test-cache.mjs
SyntaxError[ @/home/david/Projects/akasharender/akasharender/test/test-cache.mjs ]: Unexpected reserved word
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)
$ npx mocha test-cache.mjs
SyntaxError[ @/home/david/Projects/akasharender/akasharender/test/test-cache.mjs ]: Identifier 'setup' has already been declared
at ESMLoader.moduleStrategy (node:internal/modules/esm/translators:119:18)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:483:14)
This is from the real instance where the problem occurred. I had fixed the unexpected reserved word issue, only to learn of another problem — that I’d created two functions named setup
. Notice that Mocha still reported the wrong source file. But, its clear the problem will be in the other source file and not the test suite.
Conclusion
Mocha is incorrectly reporting the source file containing the code problems.
It correctly identified the problem — that some code used a reserved word incorrectly. But the error was reported in the wrong file, which can easily lead to fruitless hours carefully scrutinizing code that has no such errors.
Our time is valuable, and it’s frustrating to spend so much time cleaning up a file that had no problems in it.
Bad Mocha. No soup for you.
About the Author(s)
David Herron
:
David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.
Books by David Herron
(Sponsored)