当我发布到服务器时,无论我给auth函数的信息如何,它都会返回true。我的直觉是,我试图做同步的事情,这本质上是异步的,但我不知道如何解决它。这个咖啡代码为什么总是返回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,它的行为是否会改变? – Menztrual
否 - 没有任何区别,这使我认为auth作为其函数声明是真实的,但是它没有被执行,或者没有及时完成...... –
您的预感是正确的。你的'auth'函数会在*'redis_client.get'执行之前返回*,这就是为什么它需要回调。你不能从回调中返回,因为你不在同一个范围内。看到[这个答案](http://stackoverflow.com/questions/9310855/get-and-get-value/9310916#9310916)我的一个类似的情况和[这个答案](http://stackoverflow.com/问题/ 9362823/why-a-function-and-a-callback-non-blocking-in-node-js/9363071#9363071)解释为什么会使用这种范式。 –