2012-04-30 109 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,讓回調函數進行日誌記錄和發佈事件等等。 –