首页 > 解决方案 > 在 Firebase 函数中获取日期时间值

问题描述

我正在尝试获取服务器的日期时间值,并且我已经实现了下面的代码。但是,时间的返回值有时为空,有时无法按预期工作。

https请求代码的主要原因是检查代码今天是否已经运行,以免重复其操作。

export const helloWorld = functions.https.onRequest((request, response) => {
    response.send("Hello from Firebase!")
    const database = ref.child('Admins/currentDate')
    const timeStamp = admin.database.ServerValue.TIMESTAMP
    const currentTime = new Date(timeStamp)
    const currentDate = currentTime.getDate().toString
    const currentMonth = currentTime.getMonth().toString
    const currentYear = currentTime.getFullYear().toString
    const dateFormat = currentDate + " " + currentMonth + " " + currentYear
    database.once('value').then(function (snapshot) {
        snapshot.forEach(function (data) {
            const appTime = data.val().currentTime
            if(appTime === dateFormat){
                console.log("Points already added today." + dateFormat)
            }
            else{
                console.log("All points successfully updated." + dateFormat)
                data.ref.update({currentTime : dateFormat})
                .catch(console.error)
                udpateAllPoints()
            }
        })
    }).catch(console.error)
})

注意:updateAllPoints()用于将所有用户点数增加 10% [此代码按预期工作]

function udpateAllPoints(){
    const database = ref.child('Users')
    database.once('value').then( function (snapshot){
        snapshot.forEach(function (data){
            const points = data.val().points
            const updatedPoints = updatePoints(points)
            const userId = data.key
            data.ref.update({ points : updatedPoints})
            .catch(console.error)
            console.log("This User "+ userId +"has "+points+ "points. \n")
        })

    }).catch(console.error)

}

dateFormat 的当前示例输出如下所示:

  1. 当上面的代码运行时

    function toString() { [native code] } function toString() { [native code] } function toString() { [native code] }   
    
  2. 当移除 toString

    function { [native code] } function  { [native code] } function  { [native code] }   
    
  3. 当使用 Date.Now() 或 new Date() 而不是 new Date(timeStamp)

    NaN NaN NaN   
    

标签: typescriptfirebase-realtime-databasegoogle-cloud-functions

解决方案


您在执行函数的其余工作之前发送响应。这是行不通的。在您发送响应后,Cloud Functions 几乎会立即终止您的代码。这意味着您的数据库工作可能永远不会发生。

相反,您应该做的是仅在所有异步工作完成后才发送响应。请参考文档

使用 res.redirect()、res.send() 或 res.end() 终止 HTTP 函数。


推荐阅读