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

问题描述

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:

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

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

解决方案

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.

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

05-17 17:48