Await 是 async 函数中的保留字错误 [英] Await is a reserved word error inside async function

查看:37
本文介绍了Await 是 async 函数中的保留字错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力找出以下语法的问题:

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);
    }
  };

我不断收到错误消息:

await 是保留字

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

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

调度位来自 react-thunk 库.

The dispatch bit is coming from the react-thunk library.

推荐答案

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

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);
    }
  };

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

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.

这篇关于Await 是 async 函数中的保留字错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆