首页 > 解决方案 > Firebase 身份验证在云功能中创建用户的时间太长

问题描述

目前我遇到一个问题,调用 auth#createUser 方法最多需要 10 秒才能继续调用它的Promise#then方法。我从火力基地和谷歌云功能记录器获取这些时间戳。我觉得我可能做错了什么,虽然我无法弄清楚我做错了什么。在您说要联系 Firebase 支持之前,我已经联系过了,他们让我来这里。


const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

let database = admin.firestore();

exports.createUser = functions.https.onCall((data, response) => {
    console.log(data);
    console.log(response);

    admin.auth().createUser({
        email: data.email,
        emailVerified: false,
        password: data.password,
        displayName: data.name,
        disabled: false,
    }).then(user => {
        database.collection('users').doc(data.username).set({
            uid: user.uid,
            email: data.email,
            name: data.name,
            username: data.username
        }).catch(error => {
            throw new functions.https.HttpsError(error)
        });
        console.log('The entire thing is done successfully!');
        return {
            response: user
        }
    }).catch(error => {
        throw new functions.https.HttpsError(error);
    });
    console.log('Found my way to the end of the method');
});

标签: node.jsfirebasefirebase-authenticationgoogle-cloud-functions

解决方案


你没有正确处理承诺。onCall 函数应该返回一个promise,该promise 使用您想要返回给客户端的数据进行解析。现在,您的函数没有返回任何内容。回调中的 return 语句then实际上并没有向客户端发送任何内容。您需要做的是返回承诺链:

return admin.auth().createUser(...).then(...).catch(...)

请注意所有这些前面的返回。

此外,您将需要处理由set(). 仅仅打电话catch是不够的。您还需要从then回调中返回该承诺。

我强烈建议学习 JavaScript 中的 Promise 是如何工作的——如果没有适当的处理,你的函数将无法正常工作,并且经常以令人困惑的方式运行。


推荐阅读