Hal*_*ton 3 javascript generator koa koa-router
我一直在为koa应用编写身份验证路由器。
我有一个模块,可以从数据库获取数据,然后将其与请求进行比较。我只想yield next通过身份验证即可运行。
问题在于,与数据库通信的模块返回了一个Promise,如果我尝试yield next在该Prom中运行,则会出现错误。无论是SyntaxError: Unexpected strict mode reserved word还是SyntaxError: 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');
})
});
Run Code Online (Sandbox Code Playgroud)
我想我知道了。
需要产生promise,这将暂停功能,直到promise被解决,然后继续。
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;
}
});
Run Code Online (Sandbox Code Playgroud)
这似乎可行,但是如果遇到其他问题,我将对其进行更新。
| 归档时间: |
|
| 查看次数: |
1641 次 |
| 最近记录: |