【问题标题】:How can i get data snapshot and then update database in firebase cloud functions http request如何获取数据快照,然后在 firebase 云函数 http 请求中更新数据库
【发布时间】:2019-01-02 13:10:02
【问题描述】:

我正在尝试在云功能的 HTTPS 请求中获取 firebase 实时数据库的数据快照,然后将来自查询的值添加到快照值并再次将其设置为数据库。

这是我的代码。

exports.addCredits = functions.https.onRequest((req, res)=>{
    console.log(req.query.UserID);
    var credits = req.query.amount
    var userId = req.query.UserID

    return admin.database().ref('/Users/' + userId).once('value').then(function(snapshot) {
        var userPoints = snapshot.val().Credit
        const databaseRef = admin.database().ref("Users").child(userId+"/Credit")
        res.send("Your Credits  "+ credits + " And User ID " + userId + " user points" + userPoints);
        var total = credits + userPoints
        databaseRef.set(total);
    })
})

这是部署代码时终端出现的错误。

18:70  warning  Unexpected function expression              prefer-arrow-callback
18:70  error    Each then() should return a value or throw  promise/always-return

如何获取数据库的快照并再次写入?

【问题讨论】:

    标签: javascript firebase google-cloud-functions firebase-admin


    【解决方案1】:

    这些错误消息对 Ganesh 很有帮助,请阅读它们...

    18:70 warning Unexpected function expression prefer-arrow-callback

    是一个警告,表示你应该使用 ES6 箭头函数语法而不是带有单词“function”的老式语法:

    return admin.database().ref('/Users/' + userId).once('value').then( snapshot => {

    然后是实际的错误...

    18:70 error Each then() should return a value or throw promise/always-return

    告诉你,每次使用.then(),内部函数都需要返回一些东西。

    return admin.database().ref('/Users/' + userId).once('value').then( snapshot => {
            var userPoints = snapshot.val().Credit
            const databaseRef = admin.database().ref("Users").child(userId+"/Credit")
            res.send("Your Credits  "+ credits + " And User ID " + userId + " user points" + userPoints);
            var total = credits + userPoints
            databaseRef.set(total);
            // You are inside of a .then() block here...
            // you HAVE return SOMETHING...
            // if you want, you could do:   return databaseRef.set(total);
            // or even just:   return true;
        })
    

    【讨论】:

    • 在这种情况下,您应该返回databaseRef.set(total); 的结果,因为这是一个异步操作。如果您没有返回在该操作完成时解析的承诺,则运行您的函数的容器可能会在 set 完成之前终止代码。
    猜你喜欢
    • 1970-01-01
    • 2018-02-21
    • 2018-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多