簡體   English   中英

使用 a.then() function 時 async/await + try/catch 無法正常工作

[英]async/await + try/catch not working as spected when using a .then() function

我正在使用react進行項目,如果注冊成功,我需要重定向到登錄頁面,所以我添加了一個名為redirect的state,當您訪問我需要設置的注冊表單時為空,以便頁面可以重定向,由於我使用了處理程序,因此這是相關的組件代碼:

    class Registro extends Component {
        constructor() {
            super();
            this.state = {
                email: "",
                password: "",
                passwordConfirm: "",
                userName: "",
                redirect: "",
            };
        }
    handleRedirect = () => {
        this.setState({ redirect: "/aplicacion" });
        console.log(this.state);
    }
  render() {
        if (this.state.redirect) {
            return <Navigate to={this.state.redirect} />
          }
        
        return (
          <button id="submit" className="btn btn-outline-accesible col-3 m-2 mt-3" 
                 onClick={() => {
                 registerWithEmailAndPassword(this.state.userName, this.state.email, this.state.password).then(
                      handleRedirect() 
                 )}}>Acceder</button>

email和密碼的寄存器是這個function:

    const registerWithEmailAndPassword = async (name, email, password) => {
    try {
        console.log(name, email, password)
      const res = await createUserWithEmailAndPassword(auth, email, password);
      const user = res.user;
      await setDoc(doc(db, "users", email), {
        email: email,
        nombre: name,
        pass: password
      });
      alert("Registro completado con éxito")
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };

預期的結果是,如果注冊成功,頁面會重新加載,您可以愉快地 go,但如果出現錯誤,頁面將不會加載,並且會向用戶提示錯誤。 發生的情況是,如果出現錯誤,頁面會重定向您,然后向您顯示帶有錯誤數據的警報。

感謝您閱讀並與我一起思考這個問題。

混合方法背后的想法是什么?

這應該工作

class Registro extends Component {
  render() {
    if (this.state.redirect) {
      return <Navigate to={this.state.redirect} />;
    }

    return (
      <button
        id="submit"
        className="btn btn-outline-accesible col-3 m-2 mt-3"
        onClick={this.handleClick}
      >
        Acceder
      </button>
    );
  }

  handleClick = async () => {
    try {
      await registerWithEmailAndPassword(
        this.state.userName,
        this.state.email,
        this.state.password
      );
      handleRedirect();
    } catch (err) {
      console.error(err);
      alert(err.message);
    }
  };
}

const registerWithEmailAndPassword = async (name, email, password) => {
  console.log(name, email, password);
  const res = await createUserWithEmailAndPassword(auth, email, password);
  const user = res.user;
  await setDoc(doc(db, "users", email), {
    email: email,
    nombre: name,
    pass: password,
  });
  alert("Registro completado con éxito");
};

更新:請注意registerWithEmailAndPassword也更新以支持根據請求進行正確的錯誤處理

您的registerWithEmailAndPassword function 是async ,因此它返回Promise 在這個 function 中,您調用另一個異步 function,然后等待它的響應。 您正在捕獲setDoc引發的異常。 所以你的registerWithEmailAndPassword總是能解決。 你可以做的是:

  • 如果 function 成功返回一些東西
  • 在出錯的情況下返回被拒絕的 Promise
const registerWithEmailAndPassword = async (name, email, password) => {
    try {
        console.log(name, email, password)
      const res = await createUserWithEmailAndPassword(auth, email, password);
      const user = res.user;
      await setDoc(doc(db, "users", email), {
        email: email,
        nombre: name,
        pass: password
      });
      alert("Registro completado con éxito")
      return true
    } catch (err) {
      console.error(err);
      alert(err.message);
      return Promise.reject(false);
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM