2012-04-30 110 views
1

当我发布到服务器时,无论我给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) 
+0

谜语我这个;如果你在auth中添加一个else false,它的行为是否会改变? – Menztrual

+0

否 - 没有任何区别,这使我认为auth作为其函数声明是真实的,但是它没有被执行,或者没有及时完成...... –

+1

您的预感是正确的。你的'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)解释为什么会使用这种范式。 –

回答

1

如果你知道(或有一种预感)的东西是异步的,你应该通过什么后来做一个回调函数。我不知道你的服务器的帖子函数是如何工作的,但如果它像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 
+0

感谢您的答复 - 我是一个咖啡/节点新手(使用restify),所以我不知道我明白:|我是蟒蛇人。它更多的执行顺序我不明白..... –

+0

啊。说你使用restify的帮助。如果您想要auth同步触发,则可能需要使用节点同步。你也可以考虑把你的函数分解成更小的块,这样你就可以像next()那样传递auth,让回调函数进行日志记录和发布事件等等。 –