Javascript Await 是 async 函数中的保留字错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42299594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:02:50  来源:igfitidea点击:

Await is a reserved word error inside async function

javascriptreactjsasync-awaitredux

提问by Ilja

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

await 是一个保留字

...but isn't it legal within an async function?

...但它在异步函数中不合法吗?

The dispatch bit is coming from the react-thunklibrary.

调度位来自react-thunk库。

回答by JLRishe

In order to use await, the function directly enclosing it needs to be async. According to your comment, adding asyncto the inner function fixes your issue, so I'll post that here:

为了使用await,直接封闭它的函数需要是异步的。根据您的评论,添加async到内部函数可以解决您的问题,因此我将在此处发布:

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 asyncfrom the outer function because it does not contain any asynchronous operations, but that would depend on whether the caller of that sendVerificationEmailis expecting sendVerificationEmailto return a promise or not.

可能,您可以async从外部函数中删除 ,因为它不包含任何异步操作,但这取决于它的调用者是否sendVerificationEmail希望sendVerificationEmail返回承诺。