【问题标题】:Is there a way to catch and return a firebase error from an arrow function?有没有办法从箭头函数捕获并返回火力错误?
【发布时间】:2019-08-09 11:59:26
【问题描述】:

我想捕获并“检索”一个 firebase 错误。但是,箭头函数会发现错误。

我已经尝试返回错误,但很快意识到它正在返回到父函数,而不是返回到它被分配到的变量。我尝试了单独的 try 和 catch 块,但无济于事。

这是在 Firebase 身份验证中创建用户的相关函数。

function signupEmailPassword(form){

    //variables
    email=form['email'].value;
    password=form['password'].value;
    confirmedPassword=form['confirmPassword'].value;

    //check if passwords are matching
    if(password==confirmedPassword){

        //creates a user with an email and password

        authentication.createUserWithEmailAndPassword(email, password).then(cred=>{
            form.reset();//reset form
            sendEmailVerification();//send a verification email

        }).catch( (error)=>{
            //errors messages
            document.getElementById("message").innerHTML = error.message;
            document.getElementById("message").style.color = "red";
        })
    }else{
        //passwords do not match error message

        document.getElementById("message").innerHTML = "Passwords do not match";
        document.getElementById("message").style.color = "red";
    }
}

我想访问在单独的 javascript 文件中捕获的错误变量。所以我需要在调用函数时返回错误。

【问题讨论】:

  • 快速观察,您可以将错误传递给 catch 内的另一个函数,也许是另一个文件中的函数。你可以用 return targetFunction(error) 这样的东西来结束你的 catch 块,并且 targetFunction 期望错误作为一个参数。

标签: javascript firebase error-handling firebase-authentication


【解决方案1】:

错误处理程序可以作为回调函数传递。

var errorHandler = (error) => { 
  ...
}

function signupEmailPassword(form, errorHandler) {
...
  }).catch( (error)=>{
     //errors messages
     document.getElementById("message").innerHTML =  error.message;
     document.getElementById("message").style.color = "red";
     errorHandler(error);
  })
}

另外,Promise 可以被链接起来,这样每个 Promise 都会返回一个 Promise。这是从真正异步的角度解决问题的方法。

Promise inside promise: what's the correct way to return a variable from the child promise? (JS)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 2021-04-04
    • 2021-07-28
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多