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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0