0

I am new to JavaScript and am trying to implement something like below. Use case: implementing authentication with Firebase + JavaScript

In my sign in form, I have a JavaScript as below:

// Sign in
firebase.auth().signInWithEmailAndPassword(email, pass)
.then((user) => {
    console.log(user)
})
.catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorMessage);
});

I am trying to call a second function inside of the signInWithEmailAndPassword method. This other function looks like this:

function getMyToken() {
    firebase.auth().currentUser.getIdToken(true).then(function(idToken) {
        return idToken
    }).catch(function(error) {
        // Handle error
        console.log(error)
        return null
    });
}

How can I do that? I tried as below but getting an error:

// Sign in
firebase.auth().signInWithEmailAndPassword(email, pass)
.then((user) => {
    console.log(user)
    var isTokenDefined = getMyToken();
    if (isTokenDefined) {
       //Redirect to index.html
    }
})
.catch((error) => {
    var errorCode = error.code;
    var errorMessage = error.message;
    console.log(errorMessage);
});

Error I am getting: isTokenDefined is undefined

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
h4v3st
  • 17
  • 6
  • `getMyToken` is an asynchronous function, it takes some time to resolve. You can't just do `var isTokenDefined = getMyToken()` and expect `isTokenDefined` to be defined. This is a very common question, I have marked it as duplicate. – Jeremy Thille Aug 13 '21 at 13:16
  • if you need user where you have isTokenDefined available, you'll need to do something like `.then((user) => getMyToken().then(isTokenDefined => ......))` – Bravo Aug 13 '21 at 13:18
  • What would be the best way to resolve what I am trying to do? – h4v3st Aug 13 '21 at 13:18
  • best way? use `async`/`await` – Bravo Aug 13 '21 at 13:19
  • @Bravo, I am trying to understand async/await. Would you help me with an example based on my example above? – h4v3st Aug 13 '21 at 13:27

0 Answers0