【问题标题】:Error: Response is not valid JSON object on firebase function with onCall错误:响应不是具有 onCall 的 firebase 函数上的有效 JSON 对象
【发布时间】:2021-03-03 11:48:10
【问题描述】:

这是我的云功能代码

 exports.markThemAllRead = functions.https.onCall((data) => {
    const user = {
        id: data.id,
    }
    let batch = admin.firestore().batch();

    admin.firestore().collection("Notifications").doc("comments").collection(user.id).get().then(querySnapshot => {
        if(querySnapshot.empty){
            return "nice"
        }else {
            querySnapshot.forEach(doc=>{
                batch.update(doc.ref, {isRead:true})
            });
            return batch.commit()
        }
    }).catch(err => {
        console.log(err)
    })
    return "Good"
    })

我尝试了多种返回语句组合,但我不断收到错误:响应不是有效的 JSON 对象。谁能指导我解决问题所在?我的代码中有许多其他的 onCall 函数,但这是唯一一个与 batch.update() 相关的函数......也许与它有关?

编辑尝试

尝试此操作时仍然遇到相同的错误:

exports.markThemAllRead = functions.https.onCall((data) => {
    const user = {
        id: data.id,
    }

    return markThemRead(user)

})

async function markThemRead(user){
    let batch = admin.firestore().batch();

    const docsRef = admin.firestore().collection("Notifications").doc("comments").collection(user.id)

    const docs = await docsRef.get();

    docs.forEach(function(doc){
        batch.update(doc.ref, {isRead:true})
    })

    return batch.commit()

}

【问题讨论】:

  • 您的函数需要返回一个仅在所有异步工作完成后才解析的承诺。这个尝试立即返回“好”而不等待任何东西。另外,尝试返回一个对象,而不是一个字符串。
  • 我想我明白你在说什么。我用代码编辑了我的问题的一部分,这是你暗示的吗?

标签: reactjs firebase react-native google-cloud-firestore google-cloud-functions


【解决方案1】:

基于 Firebase 文档中的示例 Sync, async and promises

async function markThemRead(user){
    let batch = admin.firestore().batch();

    const docsRef = admin.firestore().collection("Notifications").doc("comments").collection(user.id)

    const docs = await docsRef.get();

    docs.forEach(function(doc){
        await batch.update(doc.ref, {isRead:true})
    })

    return batch.commit().then(function () { return {status: "All Good"}})

}

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 2021-01-21
    • 2020-07-26
    • 2019-08-25
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多