繁体   English   中英

如何从内部异步 function 中的外部 function 中引发错误,例如 JavaScript 中的 setTimeout?

[英]How to throw an error in the outer function from an inner async function like setTimeout in JavaScript?

我想使用 firebase 身份验证登录到我的 react 本机应用程序。 例如,要使用 email 和密码登录,我有以下 function,这基本上是一个 redux 操作:

export const userSignin = (email, password) =>
  async dispatch => {
    try {
      dispatch({ type: 'auth_attempt_started' })
      const user = await firebase.auth().signInWithEmailAndPassword(email.trim(), password)
      saveUserDataToAsyncStorage(user)
      if (!TASKS_SORT_BY && !TASKS_SORT_ORDER)
        dispatch(getTasksSortData(user.user.uid))
      if (!EMPLOYEES_SORT_BY && !EMPLOYEES_SORT_ORDER)
        dispatch(getEmployeesSortData(user.user.uid))
      if (!ACCOUNTS_SORT_BY && !ACCOUNTS_SORT_ORDER)
        dispatch(getAccountsSortData(user.user.uid))
      goToMain()
      setTimeout(() => {
        dispatch({
          type: 'user_signedin',
          payload: user
        })
      }, 100);
    }
    catch (err) {
      dispatch({
        type: 'auth_error',
        payload: err.toString()
      })
    }
  }

如果登录过程出现问题,此 function 会引发错误。 问题是当互联网连接速度很慢时,登录过程需要很长时间才能成功或失败,有时大约 30 秒左右,这对用户体验非常不利。

问题是:

如果登录过程未完成,有时可能 10 秒后我怎么能抛出错误?

谢谢!

一般来说,可以通过setTimeout来实现。

componentDidMount() {
  this.setTimeout( () => {
     this.doThisAfterTenSeconds();
  },10000);
}

doThisAfterTenSeconds() {
   // Do something
}

在这种特殊情况下,

export const userSignin = (email, password) =>
  async dispatch => {
    try {
      // Auth attempt has started
      dispatch({ type: 'auth_attempt_started' })

      // Lets add a 10 second timeout
      let hasTimedOut = false
      setTimeout(() => {
          hasTimedOut = true
          // Display message here or throw "Connection timed out"
      }, 10000)

      // Now lets await the authentication
      const user = await firebase.auth().signInWithEmailAndPassword(email.trim(), password)
      // This code should not be run if auth attempt timed out. If we throw an error the check should not be neccessary...
      if (!hasTimedOut)
      {
         saveUserDataToAsyncStorage(user)
         if (!TASKS_SORT_BY && !TASKS_SORT_ORDER)
           dispatch(getTasksSortData(user.user.uid))
         if (!EMPLOYEES_SORT_BY && !EMPLOYEES_SORT_ORDER)
           dispatch(getEmployeesSortData(user.user.uid))
         if (!ACCOUNTS_SORT_BY && !ACCOUNTS_SORT_ORDER)
           dispatch(getAccountsSortData(user.user.uid))
         goToMain()
         setTimeout(() => {
           dispatch({
             type: 'user_signedin',
             payload: user
           })
         }, 100);
         }
       }
       catch (err) {
         dispatch({
           type: 'auth_error',
           payload: err.toString()
         })
       }
     }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM