Firebase中updateEmail()函数返回值及执行结果校验问题
updateEmail() Succeeds Hey there! I see you're stuck trying to verify whether Firebase's updateEmail() actually modified a user's email. Let's break down why your current approach isn't working and fix it for good.
The Issue With Your Current Code
Firebase's updateEmail() returns a Promise object, not a direct success/failure value. A Promise is never null—even if the operation fails, the Promise itself exists (it just gets rejected). That's why your if(user.updateEmail(email) != null) check always evaluates to true, no matter if the email update worked or not.
Correct Ways to Verify Success/Failure
Since updateEmail() is asynchronous, you need to handle it using Promise-based patterns. Here are two straightforward approaches:
1. Using async/await (Clean, Modern Approach)
Wrap the call in an async function and use try/catch to separate success and error handling:
async function updateUserEmail(user, newEmail) { let msg; try { // Wait for the update operation to finish await user.updateEmail(newEmail); // If we reach here, the update succeeded! msg = "Success"; console.log("Email updated successfully"); } catch (error) { // Handle failure cases (invalid email, auth issues, etc.) msg = `Failed: ${error.message}`; console.error("Email update failed:", error); } // Use the message to notify the user or update your UI console.log(msg); }
2. Using Promise Chaining (then()/catch())
If you prefer not to use async/await, you can chain .then() for success and .catch() for errors:
let msg; user.updateEmail(email) .then(() => { // Success path: email was updated msg = "Success"; console.log("Email updated successfully"); }) .catch((error) => { // Failure path: handle the error details msg = `Failed: ${error.message}`; console.error("Email update failed:", error); });
Quick Notes
- When the update succeeds, the Promise resolves with no value—you just know it worked if it doesn't throw an error.
- If it fails (e.g., invalid email format, user not authenticated, permission issues), the Promise rejects with an
Errorobject that includes details about what went wrong.
内容的提问来源于stack exchange,提问作者raideR49

