【问题标题】:Weird behavior when accessing RowDataPacket after a callback回调后访问 RowDataPacket 时的奇怪行为
【发布时间】:2020-05-07 11:24:33
【问题描述】:

我有以下函数来检索一个 sql 行对象。

function KnownConditionByUserFarm(d, callback) {
    var where = [
        d.user_hash,
        d.id,
        d.icon,
        d.days_since,
    ]

    sql = "SELECT id, NOW() as now, time, FROM_UNIXTIME(time), date_created, DATEDIFF(NOW(), FROM_UNIXTIME(time)) as days_since FROM weathers WHERE user_hash = ? AND farm_id = ? AND icon = ? AND time > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL ? DAY));"

    query = db.query(sql, where, function (err, result) {
        if (err) {
            return callback(err, null)
        } else {
            return callback(null, result)
        }

    });
}

我可以在我的处理器功能上检索它,并且可以执行 console.log。

KnownConditionByUserFarm(data, (error, cond) => {

    if (error) {
        console.log("KnownConditionByUserFarm.Error:")
        console.log(error)
        process.exit()
    } else {

        console.log("KnownConditionByUserFarm/result")
        console.log(cond) // <-- can be accessed

    }
})

console.log(cond)的结果

KnownConditionByUserFarm/result
[ RowDataPacket {
    id: 19,
    now: 2020-05-07T03:10:20.000Z,
    time: 1587772800,
    'FROM_UNIXTIME(time)': 2020-04-24T16:00:00.000Z,
    date_created: 2020-04-24T22:16:13.000Z,
    days_since: 12 } ]

但是,当我尝试访问对象的其余部分(如 idday_since)时,我收到以下错误。

代码

console.log(cond[0].id)

错误

KnownConditionByUserFarm/result
[ RowDataPacket {
    id: 19,
    now: 2020-05-07T03:14:51.000Z,
    time: 1587772800,
    'FROM_UNIXTIME(time)': 2020-04-24T16:00:00.000Z,
    date_created: 2020-04-24T22:16:13.000Z,
    days_since: 12 } ]
19 <-- I was able to access, but it's returning cannot read property.
KnownConditionByUserFarm/result
[]
***Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

TypeError: Cannot read property 'id' of undefined

我能够访问id,但它抛出了一个奇怪的TypeError: Cannot read property 'id' of undefined

请注意,我什至尝试过

var w = JSON.parse(JSON.stringify(cond))
console.log(w[0])

结果如下:

{ id: 19,
  now: '2020-05-07T03:22:24.000Z',
  time: 1587772800,
  'FROM_UNIXTIME(time)': '2020-04-24T16:00:00.000Z',
  date_created: '2020-04-24T22:16:13.000Z',
  days_since: 12 }

当我访问id

console.log(w[0].id)

结果:

*/Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

TypeError: Cannot read property 'id' of undefined

可能缺少什么?

【问题讨论】:

    标签: javascript node.js callback node-mysql


    【解决方案1】:

    我不知道我遇到的问题可能是什么原因,但我能够通过再次执行并仔细记录来解决它,直到我得到我需要的。

    var w = JSON.stringify(cond[0])
    console.log(w)
    
    var p = JSON.parse(w)
    console.log(p)
    
    console.log(p.id)
    console.log(p.days_since)
    
    var ps = JSON.parse(JSON.stringify(cond[0]))
    console.log(ps.days_since)
    

    【讨论】:

      猜你喜欢
      • 2012-02-25
      • 1970-01-01
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多