【问题标题】:Why is this coffeescript code always returning true?为什么这个咖啡脚本代码总是返回 true?
【发布时间】:2012-05-09 22:00:17
【问题描述】:

当我发布到服务器时,无论我给 auth 函数提供什么信息,它都会返回 true。我的预感是我正在尝试同步做一些事情,这本质上是异步的,但我不知道如何解决它。

auth = (username, api_key, device) ->
  hashed_key = hash.sha256(username + api_key + device, salt) 
  winston.debug('Checking auth for ' + username)
  redis_client.get hashed_key, (err, data) ->
    if data == username
        true

# Main Handler for posting data for a device.
server.post "/:customer/:site/:device", create = (req, res, next) ->
    message = JSON.parse(req.body)
    winston.info(server.name + ': Recieved event from ' + req.params.device)
    authenticated = auth(message.username, message.api_key, message.device)
    winston.debug('****' + authenticated)
    if authenticated == true 
        winston.debug('Auth passed, got a valid user/device/api combination: ' + message.username)
        redis_client.publish('device_events', req.body)
        return next()
    else
        winston.debug('Auth failed, cant find device ' + message.device + ' for ' + message.username)
        return next(restify.NotAuthorizedError)

【问题讨论】:

  • 这个谜语;如果在 auth 中添加 else false,它的行为会改变吗?
  • 不 - 没有区别,这让我认为 auth 作为一个函数声明是正确的,但它要么没有被执行,要么没有及时完成......跨度>
  • 你的预感是正确的。您的 auth 函数将返回 before redis_client.get 已执行——这就是它需要回调的原因。您无法从回调中返回,因为您不再处于同一范围内。请参阅我的this answer 了解类似情况,并参阅this answer 了解为什么要使用此范例的解释。

标签: node.js coffeescript redis


【解决方案1】:

如果您知道(或有预感)某事是异步的,您应该将之后要执行的操作作为回调函数传递。我不确定您服务器的 post 功能是如何工作的,但如果它像 Node HTTP's request 您应该执行以下操作:

get = (location, callback, retriever, filterer, formatter)->
  decoratedCallback = (data)->
    callback formatter.applyFormat filterer.applyFilter data
  retriever.retrieve location, decoratedCallback

module.exports = get

【讨论】:

  • 感谢您的回复 - 我是咖啡/节点新手(使用 restify),所以我不确定我是否理解:|我是蟒蛇人。它更多的是我不明白的执行顺序.....
  • 啊。说你使用 restify 会有所帮助。如果您希望 auth 同步触发,您可能需要使用 node-sync。您可能还想考虑将您的函数分解成更小的块,这样您就可以将身份验证作为 next() 传递,让该回调执行日志记录和发布事件等
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 2018-02-13
  • 2014-01-13
  • 1970-01-01
相关资源
最近更新 更多