首页 > 解决方案 > Firebase Cloud Functions 检查是 snapshot.exists() 错误

问题描述

当我尝试运行一个函数时

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

exports.checkPostsRef = functions.https.onRequest((request, response) => {

    const postId = 'foo'

    admin.database().ref('/posts/' + postId).once('value', snapshot => {

        if !snapshot.exists() {
            console.log("+++++++++ post does not exist +++++++++") // I want this to print
            return
        }
    });
});

我不断收到以下错误Parsing error: Unexpected token snapshot

在此处输入图像描述

一旦我注释掉一切是否snapshot.exists() { .... } 正常

我正在关注这个链接,上面说有一个.exists()功能,那么为什么我会遇到这个问题?

在此处输入图像描述

标签: node.jsfirebase-realtime-databasegoogle-cloud-functions

解决方案


原来return;是导致问题的语句。我不得不改用一个if-else语句。

编辑正如@FrankvanPuffelen 在问题下方的评论和他的回答中指出的那样,这个问题与return声明无关,而与我最初拥有!snapshot.exists(). (!snapshot.exists())因为它没有被括在导致问题的括号中。所以这不是return声明,我对 Javascript 知之甚少,并且使用了错误的语法

if (!snapshot.exists()) {

    console.log("+++++++++ post does not exist +++++++++");

} else {

    console.log("--------- post exists ---------");
}

仅供参考,我是本地 Swift 开发人员,在 Swift 中,您不需要在括号中包含任何内容。在 Swift 中,你可以这样做:

let ref = Database.database().reference().child("post").child("foo")
ref.observeSingleEvent(of: .value, with: { (snapshot) in

    if !snapshot.exists() {
        print("+++++++++ post does not exist +++++++++")
        return
    }
})

推荐阅读