如何从登录导出async变量



我正在尝试从登录导出用户信息到其他模块。

export function login(){
console.log("entrando A LOGIN")    
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth()
.signInWithPopup(provider)
.then((result) => {
/** @type {firebase.auth.OAuthCredential} */
var credential = result.credential;      
var token = credential.accessToken;
// The signed-in user info.
let user = result.user;
module.exports.user=user  /// it says it does not provide user variable when in this ine I am 
doing it

}等等……

///它说它不提供用户变量,但我提供了。谢谢我是新人

据我所知,您根本不需要使用module.exports。你真的不想把它们和es6模块混在一起。

// google-auth.js
export function login() {
const provider = new firebase.auth.GoogleAuthProvider();
return firebase.auth()
.signInWithPopup(provider)
.then((result) => {
const credential = result.credential;      
const token = credential.accessToken;
const user = result.user;
return user; 
})
.catch(error => {
// you deal with errors that happen here
})
}

通过从函数返回用户对象来获得它。函数返回一个promise所以,如果你尝试像const user = login()这样做它是行不通的要将函数导入到另一个文件中并以一种可以访问用户对象的方式使用它,你可以这样做:

// login.js
import { login } from './path/to/google-auth.js'
const authInstance = login();

来自官方文档:

import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
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;
// ...
}).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);
// ...
});

最新更新