Node.js 为什么这个coffeescript代码总是返回true?

Node.js 为什么这个coffeescript代码总是返回true?,node.js,coffeescript,redis,Node.js,Coffeescript,Redis,当我发布到服务器时,不管我给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 h

当我发布到服务器时,不管我给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)
如果您知道(或有预感)某些东西是异步的,那么您应该将之后要做的事情作为回调函数传递。我不确定您的服务器的post功能是如何工作的,但如果您认为应该执行以下操作:

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

module.exports = get
如果您知道(或有预感)某些东西是异步的,那么您应该将之后要做的事情作为回调函数传递。我不确定您的服务器的post功能是如何工作的,但如果您认为应该执行以下操作:

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

module.exports = get

给我猜这个谜语;如果你在auth中添加一个else false,它的行为会改变吗?不-没有区别,这让我认为auth作为一个函数声明是真的,但它要么没有被执行,要么没有及时完成……你的直觉是正确的。您的
auth
函数将在执行
redis\u client.get
之前返回,这就是它需要回调的原因。您不能从回调返回,因为您不再在同一范围内。请看我的例子,了解类似的情况,以及为什么要使用这个范例的解释;如果你在auth中添加一个else false,它的行为会改变吗?不-没有区别,这让我认为auth作为一个函数声明是真的,但它要么没有被执行,要么没有及时完成……你的直觉是正确的。您的
auth
函数将在执行
redis\u client.get
之前返回,这就是它需要回调的原因。您不能从回调返回,因为您不再在同一范围内。请参阅我的文章,了解类似的情况以及为什么要使用此范例的解释。感谢您的回复-我是咖啡/节点新手(使用restify),所以我不确定我是否理解:|我是python人。我更不明白执行的顺序……啊。说你使用restify有帮助。如果要同步激发auth,可能需要使用节点同步。你也可以考虑把你的函数分解成更小的块,这样你可以把Authas作为下一个(),调用一个调用,记录和发布事件等等。谢谢你的回复——我是一个咖啡/节点新手(使用RealStudio),所以我不确定我理解:我是Python家伙。我更不明白执行的顺序……啊。说你使用restify有帮助。如果要同步激发auth,可能需要使用节点同步。你也可以考虑把你的函数分解成更小的块,这样你就可以将AUTH传递到下一个(),让它调用一个调用,记录和发布事件等等。