【发布时间】:2018-03-08 18:10:07
【问题描述】:
我对目标 es2017 的打字稿上的 async/await 有疑问。以下是我的代码:
我的 route.ts :
method: 'POST',
config: {
auth: {
strategy: 'token',
}
},
path: '/users',
handler: (request, reply) {
let { username, password } = request.payload;
const getOperation = User
.findAll({
where: {
username: username
}
})
.then(([User]) => {
if(!User) {
reply({
error: true,
errMessage: 'The specified user was not found'
});
return;
}
let comparedPassword = compareHashPassword(User.password, password);
console.log(comparedPassword);
if(comparedPassword) {
const token = jwt.sign({
username,
scope: User.id
}, 'iJiYpmaVwXMp8PpzPkWqc9ShQ5UhyEfy', {
algorithm: 'HS256',
expiresIn: '1h'
});
reply({
token,
scope: User.id
});
} else {
reply('incorrect password');
}
} )
.catch(error => { reply('server-side error') });
};
我的 helper.ts :
export async function compareHashPassword(pw:string, originalPw:string) {
console.log(pw);
console.log(originalPw);
let compared = bcrypt.compare(originalPw, pw, function(err, isMatch) {
if(err) {
return console.error(err);
}
console.log(isMatch);
return isMatch;
});
return await compared;
}
此身份验证路由应该在用户登录时返回 JWT 令牌。但这里的问题是即使我输入有效密码登录函数 compareHashPassword 总是返回未定义。
例如当我用 json 字符串调用 api 时
{
"username": "x",
"password": "helloword"
}
当我使用 console.log() 进行跟踪时,日志是:
$2a$10$Y9wkjblablabla -> hashed password stored in db
helloword
Promise {
<pending>,
domain:
Domain {
domain: null,
_events: { error: [Function: bound ] },
_eventsCount: 1,
_maxListeners: undefined,
members: [] } }
true
也许这只是我对使用 async/await 和 typescript 缺乏了解。注意我的环境是:
node : v8.6.0
typescript : v2.5.2
ts-node : v3.3.0
my tsconfig.json //
{
"compilerOptions": {
"outDir": "dist",
"target": "es2017",
"module": "commonjs",
"removeComments": true,
"types": [
"node"
],
"allowJs": true,
"moduleResolution": "classic"
},
"exclude": [
"node_modules"
]
}
【问题讨论】:
标签: node.js typescript asynchronous async-await sequelize.js