1

I'm developing an app with a Sign In with Google Firebase. I've got the need to update de current user data wich exists within a Auth Module when a user sign in, and then chain the execution of stuff with that specific data. Something like this :

fbAuth.signInWithGoogle()
.then(()=>{
    let user = fbAuth.getCurrentUser()
    console.log(user);
    fbFirestore.postDocToExistingGroup("projects", user.uid, {user: user.uid, test:true})
})

So I coded the function as a Promise inside a module Pattern function named fbAuth, but it seems to not be the best way for me:

const signInWithGoogle = function(){
        return Promise.resolve(
            signInWithPopup(auth, provider)
            .then((result) => {
            // This gives you a Google Access Token. You can use it to access the Google API.
            const credential = GoogleAuthProvider.credentialFromResult(result);
            const token = credential.accessToken;
            // The signed-in user info.
            const user = result.user;
            setCurrentUser(user)
            console.log("Signed In", user)
            // ...
            }).catch((error) => {
            // Handle Errors here.
            const errorCode = error.code;
            const errorMessage = error.message;
            // The email of the user's account used.
            const email = error.email;
            // The AuthCredential type that was used.
            const credential = GoogleAuthProvider.credentialFromError(error);
            // ...
            })
        )
    }

I did that just to be sure that I've got the current user data to execute the rest of the code using that data and not because the function its suposed to be a Promise from the beginning.

Jesus Esis
  • 15
  • 3
  • 2
    remove the surrounding `Promise.resolve` ... does the code still work? hint: it will, as long as you ONLY remove `Promise.resolve(` and `)` ... i.e. `return signInWithPopup(auth, provider).etc` – Bravo Apr 27 '22 at 02:17
  • 2
    Since `signInWithPopup` returns a thenable already, wrapping it in another almost certainly won't accomplish anything – CertainPerformance Apr 27 '22 at 02:20
  • @Bravo You're right, it was my fault not returning the Promise that already exists... – Jesus Esis Apr 27 '22 at 02:27
  • "*not because the function its supposed to [return] a Promise from the beginning.*" - but it does! It's doing something asynchronous, so it should return a promise. (Even better though would be if you fulfilled the promise with the `user`, so that you can just use `.then((user)=>{ … }` instead of having to call `fbAuth.getCurrentUser()`) – Bergi Apr 27 '22 at 03:14
  • "*`// Handle Errors here.`*" - not sure if that's the correct place. Notice that your `then` handler calling `fbFirestore.postDocToExistingGroup(…)` will still be executed after you've had an error - is that intended? – Bergi Apr 27 '22 at 03:15

0 Answers0