【问题标题】:How do I share information between functions on Firebase realtime database如何在 Firebase 实时数据库上的函数之间共享信息
【发布时间】:2020-09-05 10:27:44
【问题描述】:

我现在正在用 react-native 开发一个项目,并且我集成了 firebase 来处理我的数据。 我现在正在处理函数中的 index.js 文件。

所以基本上我要做的是通过使用 .onCreate 函数在创建用户后检索用户的信息,并在 .onCreate 中使用相同的信息> 订单功能。

我试图将我的信息存储在全局变量中,但它不起作用,它显示为未定义。

可能在图像中会更好地解释。

This is where i am having problems

var username;

// ------------ USER DATA FUNCTION ------
exports.requestUserData = functions.database.ref('/users/{userId}/{autoGen}')
.onCreate((snap, context) => { 
    username = snap._data.name;
    console.log(` Username: ${username}`);
});


// ---- ORDERS FUNCTION -----
exports.sendEmail = functions.database.ref('/orders/{userId}/{orderId}/')  
    .onCreate((snap, context) => { 
    const userId = context.params.userId;
  // USERNAME IS WHAT I NEED TO GET TO USE IN THIS FUNCTION

        console.log(`THIS IS WHAT I AM EXPECTING TO GET! --> ${username}`);

编辑:如果不可能,那么我可以在另一个函数中向数据库发出请求吗?

非常感谢您的帮助!

【问题讨论】:

标签: javascript firebase react-native firebase-realtime-database google-cloud-functions


【解决方案1】:

Cloud Functions 无法通过共享全局变量共享信息。每个函数彼此完全独立运行并且没有共享状态。您将不得不找到一种通过其他方式共享数据的方法,例如数据库中的另一个位置。

我建议观看此内容以获取更多信息:https://www.youtube.com/watch?v=rCpKxpIMg6o

【讨论】:

    【解决方案2】:

    正如 Doug 所说,您不能通过全局变量在不同的 Cloud Functions 之间共享信息。这两个函数在不同的容器中运行。但即使它们在同一个容器上运行,也不能保证 requestUserData 会在 sendEmail 之前被调用。

    相反,您需要读取 sendEmail 函数中的用户名,如下所示:

    var 用户名;

    exports.sendEmail = functions.database.ref('/orders/{userId}/{orderId}/')  
        .onCreate((snap, context) => { 
        const userId = context.params.userId;
        return snapshot.ref.root.child(`/users/${userId}/name`).once("value).then((nameSnapshot) => {
            const username = nameSnapshot.val();
            console.log(username);
    
            ... any code that needs the username
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多