【发布时间】:2017-01-28 06:46:45
【问题描述】:
我正在尝试将 bcrypt 模块用于 Node 和 TypeScript 的 await / async 选项。 compare 代码相当简单:
let compare = util.asyncWrap( bcrypt.compare );
let result = await compare( password, stored );
return result;
当我通过 TypeScript 编译器运行它时,它会说:
错误 TS2322:类型“{}”不可分配给类型“布尔”。
好吧,很公平,它不知道来自compare 的解析值将是一个布尔值。问题是,我该怎么说呢?只需将 :boolean 添加到 result 对象即可移动错误。
这是我的asyncWrap 函数:
export default function asyncWrap( fn ) {
return function (...args) {
return new Promise( function ( resolve, reject ) {
// Assume the callback handler goes at the end of the arguments
args.push( function( err, val ) {
// Assume that err is the first argument and value is the second
if ( err ) {
reject( err );
}
else {
resolve( val );
}
} );
fn.apply( fn, args );
} );
}
}
我应该注意,我知道我可以使用来自 npm 的 bcrypt 的 promified 版本,但是,我刚刚开始使用 TypeScript,想了解它是如何工作的。
【问题讨论】:
标签: node.js asynchronous typescript bcrypt