首页 > 解决方案 > 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

标签: typescriptexpressrest

解决方案


JavaScript本质上是异步的。根据您的程序判断,console.log将在awaited 函数完成之前运行。因此,解决此问题的方法如下:

使用 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 处理得更好。


推荐阅读