首页 > 解决方案 > Firebase 函数承诺未定义的 TypeError

问题描述

我目前正在使用 firebase 函数从数据库中调用以下文档:

let token, userId;
db.doc(`/users/${newAccount.username}`)
    .get()
    .then((doc) => {
        if (doc.exists === false) {
            return firebase.auth().createUserWithEmailAndPassword(newAccount.email, newAccount.password).catch(err => console.error(err));
        } else {
            res.status(400).json({ username: 'this username is already taken' });
        }

    })

    .then(data => {
        userId = data.user.uid;
        return data.user.getIdToken();
    })

    .then((idToken) => {
        token = idToken;
        const userCredentials = {
            username: newAccount.username,
            email: newAccount.email,
            created: new Date().toISOString(),
            userId
        };
        return db.doc(`/users/${newAccount.username}`).set(userCredentials);

    })

    .then(() => {
        return res.status(201).json({ token });
    })
    .catch((err) => {
        console.error(err);
        if (err.code === 'auth/email-already-in-use') {
            return res.status(400).json({ email: 'Email is already is use' });
        } else {
            return res.status(500).json({ general: 'Something went wrong, please try again' });
        }
    });

如果文档存在于数据库中,则代码运行良好,但会记录错误:

TypeError: Cannot read property 'user' of undefined

我认为承诺仍在运行,我对如何结束它有点困惑?

任何帮助将不胜感激。谢谢。

标签: javascriptnode.jsfirebasefirebase-realtime-database

解决方案


您的第二个then回调将在所有情况下被调用。在第一个回调中发送 400 响应实际上并不会阻止 Promise 传播到所有以下then回调。

如果要停止then执行回调链,则应改为抛出错误以被链下的 a 拾取catch,跳过所有then.


推荐阅读