Firebase v3 createUserWithEmailAndPassword。然后是Promise

时间:2016-07-21 18:00:38

标签: firebase firebase-realtime-database firebase-authentication

Firebase v3 Reference Guide表示createUserWithEmailAndPassword(email, password)返回包含非空firebase.Promise的{​​{1}}。

Firebase v3 Authenticate with Firebase using Password-Based Accounts Guide显示以下示例

firebase.User

我的问题是,我想触发一个函数,将用户添加到我的实时数据库中的firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // ... }); 节点。我想要包括我从网站注册表单中收集的用户显示名称。所以,似乎我想要users并且如果.then方法成功,我想触发一个将新用户(带有显示名称)写入我的实时数据库{{1}的函数} node。

如何将示例脚本修改为createUserWithEmailAndPassword样式?

4 个答案:

答案 0 :(得分:31)

以下是对then()的正确使用以及createUserWithEmailAndPassword的错误处理:

firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
    var user = firebase.auth().currentUser;
    logUser(user); // Optional
}, function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
});

function logUser(user) {
    var ref = firebase.database().ref("users");
    var obj = {
        "user": user,
        ...
    };
    ref.push(obj); // or however you wish to update the node
}

我有另一个例子here

答案 1 :(得分:3)

选中此项,您需要阅读有效负载或快照(firebase术语)

firebase.auth().createUserWithEmailAndPassword(credentials.email, credentials.password)
                .then((authData) => {
                    console.log("User created successfully with payload-", authData);
                    //Write code to use authData to add to Users
                }).catch((_error) => {
                    console.log("Login Failed!", _error);
                })

答案 2 :(得分:2)

这就是我的所作所为。

        function registerUsername(email,password,displayName){
            firebase.auth().createUserWithEmailAndPassword(email, password).then(function(value) {
                console.log(value);
                }).catch(function(error) {
                    console.log(error);
                });
        }

答案 3 :(得分:0)

为将来偶然发现,一个等待异步的例子:

export const doCreateUserWithEmailAndPassword = async (pEmail, pPassword) => {
    try {
        const authResult = await app.auth().createUserWithEmailAndPassword(pEmail, pPassword);
         usersRef.doc(authResult.user.uid)
            .set({
                email: pEmail,
                created: firebase.firestore.FieldValue.serverTimestamp(),
              });
    }
    catch(error){
        console.log(error);
    }
}