javascript - Firebase 检查节点是否存在返回 true 或 false

标签 javascript firebase firebase-realtime-database google-cloud-functions

我有这个 Firebase 实时数据库: Firebase tree

我正在制作约会应用程序,类似于我的单例汉的 Tinder。我现在正在创建匹配系统。

我创建了 onCreate 监听器来检查用户何时按下“like”按钮,并检查其他用户是否已经对当前用户按下了“like”。这就是我尝试过的。

exports.UserPressesLike = functions.database
  .ref('/users/{userId}/matches/{otherUserId}')
  .onCreate((snapshot, context) => {
    // Grab the current value of what was written to the Realtime Database.
    const original = snapshot.val();
    const userId = context.params.userId;
    const matchedUserId = context.params.otherUserId;
    const a = checkUserMatch(userId, matchedUserId);
    if (a === true) {
      console.log('Its a match');
    } else {
      console.log('There is no match');
      console.log(a);
    }

    return null;
  });

checkUserMatch = async (userId, matchedUserId) => {
  const snapshot = await admin
    .database()
    .ref('/users/' + matchedUserId + '/matches/' + userId)
    .once('value')
    .then(snapshot => {
      // let tempuserId = snapshot.val();
      // if()
      return true;
    });
};

我希望 checkUserMatch 如果存在该节点则返回 true,如果不存在该节点则返回 false。

最佳答案

您的 checkUserMatch 是异步的(如您用 async 标记的事实所示),这意味着它不会立即返回值,而是返回一个对象最终将包含一个值(所谓的 promise )。

要调用async函数,您需要使用await来调用它:

const a = await checkUserMatch(userId, matchedUserId);

这意味着您还需要将包含调用的函数标记为异步,因此:

exports.UserPressesLike = functions.database
  .ref('/users/{userId}/matches/{otherUserId}')
  .onCreate(async (snapshot, context) => {

请注意,我强烈建议您在了解有关异步 API、Promises 和 async/await 的更多信息之前不要继续。例如,通过观看 Doug 的视频系列 Learn JavaScript Promises with HTTP Triggers in Cloud Functions .

关于javascript - Firebase 检查节点是否存在返回 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60812104/

相关文章:

javascript - 动态 javascript 选择下拉菜单

javascript - JsFiddle 中的代码不起作用

ios - Facebook SDK 和 Firebase

firebase - Firebase 达到 100 个并发连接限制后何时允许新连接?

Android:从 Firebase 读取对象会导致应用程序崩溃

java - "Couldn' t 查找具有权限 com.google.firebase.database.provider 的提供商的元数据”

android - 如何使用 firebase 数据库引用在 android studio 中创建带有代码的节点

javascript - JQuery 表单插件向 Node.js 发送空数据?

javascript - 使用 PHP 创建 JavaScript 函数,由 jQuery 返回,稍后从页面调用

swift - 从数据库中获取特定数据并打印