2015-12-21 31 views
3

我一直在爲一個koa應用程序編寫身份驗證路由器。如何在承諾或回調中運行`yield next`?

我有一個模塊,從數據庫獲取數據,然後將其與請求進行比較。如果驗證通過,我只想運行yield next

問題是與DB通信的模塊返回一個承諾,如果我嘗試在該承諾中運行yield next,則會收到錯誤消息。取決於是否使用嚴格模式,可以是SyntaxError: Unexpected strict mode reserved wordSyntaxError: Unexpected identifier

這裏有一個簡單的例子:

var authenticate = require('authenticate-signature'); 

// authRouter is an instance of koa-router 
authRouter.get('*', function *(next) { 
    var auth = authenticate(this.req); 

    auth.then(function() { 
    yield next; 
    }, function() { 
    throw new Error('Authentication failed'); 
    }) 
}); 

回答

3

我想我想通了。

承諾需要產生,這將暫停功能,直到承諾解決,然後繼續。

var authenticate = require('authenticate-signature'); 

// authRouter is an instance of koa-router 
authRouter.get('*', function *(next) { 
    var authPassed = false; 

    yield authenticate(this.req).then(function() { 
    authPassed = true; 
    }, function() { 
    throw new Error('Authentication failed'); 
    }) 

    if (authPassed) { 
    yield next; 
    } 
}); 

這似乎工作,但我會更新這個,如果我遇到更多的問題。

-1

您只能使用yield發電機裏面,但你必須通過Promisethen回調是正常的功能,這就是爲什麼你會得到一個SyntaxError。

你可以把它改寫如下:

var authenticated = yield auth.then(function() { 
    return true; 
}, function() { 
    throw new Error('Authentication failed'); 
}) 

if (authenticated) yield next 
+0

這是行不通的,因爲'auth.then'中的回調只有在if塊之後纔會運行。它是異步的。此外,回調的返回值不會存儲在變量'authenticated'中。 「認證」只是另一個承諾。 –

+0

對不起,我忘了'yield'我向你保證它可以工作,因爲我已經和Koa一起工作了幾個月,這就是我的做法。 – Tae

+0

它不會,因爲變量'authenticated'只是一個承諾,所以if語句總是會通過。如果你看看我的答案,那就應該怎麼做。你得到承諾,然後將結果保存在一個變量中,然後你可以將該變量用於if語句。 –