typescript - Typescript/Express 中的变量问题
问题描述
我正在尝试使用 TS 和 Express 的 rest api。对于登录部分,我必须预先生成salt
以加密密码并继续。看看这段代码:
const { user, pwd } = req.body;
let salt : String = ""; //Declared empty
let hash : String = ""; //Declared empty
(await DB).query("select salt from sf_guard_user where username = ?", [user])
.then(function(data) {
salt = data[0].salt;
hash = crypto.createHash('sha1').update(salt + pwd).digest('hex');
});
console.log(salt, hash); //Still empty
//...
如何在我的外部访问这些值query
?
解决方案
JavaScript本质上是异步的。根据您的程序判断,console.log
将在await
ed 函数完成之前运行。因此,解决此问题的方法如下:
使用 Promises(就像你在示例中所做的那样):
(await DB).query("select salt from sf_guard_user where username = ?", [user])
.then(function(data) {
salt = data[0].salt;
hash = crypto.createHash('sha1').update(salt + pwd).digest('hex');
console.log(salt, hash);
// do rest of function here...
});
这将确保console.log
在异步函数完成后运行。所有Promise
的s/异步函数都是这样的。
进一步阅读:MDN 文档中的承诺。
注意:在我看来,使用 newasync/await
比使用 Promises 更好,但有些情况下使用 Promises 处理得更好。
推荐阅读
- mule - 在单个有效负载中合并 2 个或更多数组
- visual-studio - 每个 VisualStudio 的 Outlook 插件 - 按钮事件处理程序
- reactjs - React-fullscreen 不工作:goFull 方法没有被触发
- dart - 如何从 \n 中删除字符以以字符串结尾
- javascript - React&Redux:我在后台有状态,但无法在我的 JSX 中呈现循环数组
- html - 下拉列表不显示名称值
- vapor - 升级到 Vapor 4:如何创建模型并返回它
- scala - 如何使用 Circe 将案例类转换为 Map[String, Object]
- r - 过滤 col A != col B 的数据
- signal-processing - 我们如何提高 Librosa 中的节奏检测精度?