首页 > 解决方案 > Firebase 错误:函数返回未定义、预期的 Promise 或值

问题描述

我很感激这个问题已经在几个地方得到了回答。我是 Firebase 云功能(和学习 TS)的新手,所以我只想在我自己的上下文中查看解决方案,以充分理解这里的问题。

我的 index.ts:

exports.OnPlanCreate = functions.database
.ref(`users/{uid}/plans/{key}`)
.onCreate((snapshot, context) => {
    const user: string = context.params.uid
    const fBaseKey: string = context.params.key
    // const plan: any = snapshot.val()
    console.log(`New plan created with key ${fBaseKey}for user ${user}`)

    // Update plan object key with Firebase generated DB key
    snapshot.ref.update({ key: fBaseKey })
    .then(() => {
        console.log('Plan key auto updated successfully!')
    })
    .catch((e) => {
        console.error(e)
    })
})

给出警告:“函数返回未定义、预期的 Promise 或值”

我很感激能帮助我理解将来使用的正确模式的解释:)

非常感谢!

标签: firebasegoogle-cloud-functions

解决方案


这意味着你需要从你的函数中返回。所以试试这个,它应该工作:

exports.OnPlanCreate = functions.database
.ref(`users/{uid}/plans/{key}`)
.onCreate((snapshot, context) => {
    const user: string = context.params.uid
    const fBaseKey: string = context.params.key
    // const plan: any = snapshot.val()
    console.log(`New plan created with key ${fBaseKey}for user ${user}`)

    // Update plan object key with Firebase generated DB key
    return snapshot.ref.update({ key: fBaseKey })
    .then(() => {
        console.log('Plan key auto updated successfully!')
    })
    .catch((e) => {
        console.error(e)
    })
})

如果您想了解 Typescript 和 Cloud Functions,这是一个很好的起点: https ://firebase.google.com/docs/functions/terminate-functions

此外,如果您需要真实的示例,还有Firebase 拥有的一个很棒的GitHub存储库。享受 :)


推荐阅读