Azhar Razak
Azhar Razak

Reputation: 15

How to get the promise state when creating a new Auth user in firebase using javascript

I am able to create a new user in firebase Authentication like this:

const status = firebase.auth().createUserWithEmailAndPassword(email, password);   
console.log(status);

The console shows the output as this:

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: FirebaseError: Firebase: The email address is badly formatted.

How would I get the PromiseState from my status variable?

Upvotes: 0

Views: 273

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 85112

The promise state is whether the promise resolves or rejects. If you're using the .then approach to working with promises, you can supply a second callback function to handle the error case:

firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(status => {
    // If it gets to here, the promise resolved
    console.log(status);
  }, error => {
    // If it gets to here, the promise rejected
    console.log(error);
  });

// Or, equivalently:
firebase.auth().createUserWithEmailAndPassword(email, password)
  .then(status => {
    console.log(status);
  })
  .catch(error => {
    console.log(error);
  });

If you're using async/await, then you handle the error case with a try/catch

async someFunction() {
  try {
    const status = await firebase.auth().createUserWithEmailAndPassword(email, password);
    // If it gets to here, the promise resolved
    console.log(status);
  } catch (error) {
    // If it gets to here, the promise rejected
    console.log(error);
  }
}

Upvotes: 2

Related Questions