Await is a reserved word error inside async function
JavascriptReactjsAsync AwaitReduxJavascript Problem Overview
I am struggling to figure out the issue with the following syntax:
export const sendVerificationEmail = 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);
}
};
I keep getting error saying:
> await is a reserved word
...but isn't it legal within an async function?
The dispatch bit is coming from the react-thunk library.
Javascript Solutions
Solution 1 - Javascript
In order to use await
, the function directly enclosing it needs to be async. According to your comment, adding async
to the inner function fixes your issue, so I'll post that here:
export const sendVerificationEmail = async () =>
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);
}
};
Possibly, you could remove the async
from the outer function because it does not contain any asynchronous operations, but that would depend on whether the caller of that sendVerificationEmail
is expecting sendVerificationEmail
to return a promise or not.
Solution 2 - Javascript
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.