【问题标题】:Promise with node-postgres queries always returns undefined使用 node-postgres 查询的 Promise 总是返回 undefined
【发布时间】:2021-06-11 15:14:20
【问题描述】:

我在评估使用 node-postgres 查询的函数的结果时遇到问题,它总是返回“未定义”(此函数验证数据库中 JWT 令牌信息的有效性):

const testTokenQuery = function(account_id, is_admin, query) {
  return new Promise(function(resolve, reject){
    pool.query(query, [account_id], function(err, result) {
        if(err) {
          reject("invalid")
        }
        else {
          const bdd_account_id = String(JSON.stringify(result.rows[0].ac_account_id)).replace(/['"]+/g, '')
          const bdd_is_admin = String(JSON.stringify(result.rows[0].ac_isadmin)).replace(/['"]+/g, '')
          if (account_id == bdd_account_id || tok_is_admin == bdd_is_admin){
            resolve ("valid")
          }
          else {
            reject("invalid")
          }

        }
    })
    pool.end();
  })
}

const testToken = (token) => {
  const checkTokenId_query = sql = fs.readFileSync('./sqlqueries/checkTokenId_query.sql').toString()
  const decodedToken = jwt.decode(token, 'JWT_SIGN_SECRET')
  const tok_account_id = decodedToken.account_id
  const tok_is_admin = decodedToken.isadmin
  testTokenQuery(tok_account_id, tok_is_admin, checkTokenId_query)
    .then(function(result){
      console.log(result) //===================> It allways return the good value here
  }).catch(function(err){
    console.log(err);   
  })
}


const isvalid = testToken('eyJhbGciO............ltJT0PhXCjV00')
if(isvalid == "valid") {
  console.log("valid token")
}
else if(isvalid == "invalid") {
  console.log("not a valid token")
}
else{
  console.log("I don't know : " + isvalid) //======> Always the result with isvalid = undefined
}

SQL 查询文件包含:

SELECT  ac_account_id,
            ac_isadmin,
            ac_isactive
FROM    table_accounts
WHERE ac_account_id = $1;

结果总是“我不知道:未定义”,而 testTokenQuery 的 console.log(result) .then 返回“有效”...

我用回调测试:同样的问题,等待/异步:同样的问题......我快疯了......

感谢帮助!

问候。

更新: 我试图在极端简化以使用异步进行测试,但我仍然有“未定义”作为答案:

const testTokenQuery = async (account_id, query) => {
    pool.query(query, [account_id], function(err, result) {
      return String(JSON.stringify(result.rows[0].ac_account_id))
    })
}
const testToken = async (token) => {
    const checkTokenId_query = sql = fs.readFileSync('./sqlqueries/checkTokenId_query.sql').toString()
    const decodedToken = jwt.decode(token, 'JWT_SIGN_SECRET')
    const tok_account_id = decodedToken.account_id
    return await testTokenQuery(tok_account_id, checkTokenId_query)
}

const tokenReturn = async (token) => {
    console.log(await testToken(token))
}

tokenReturn('eyJhbGciOiJ...........0PhXCjV00')

【问题讨论】:

  • pool.end() 在 pool.query() 回调解决之前触发

标签: node.js node-postgres


【解决方案1】:

老实说,我之前没有使用过“node-query”,但我只是探索了this issue talk(这是关于 .end(),所以我认为这不是问题)。

从您的代码中,我相信原因是您调用了函数本身,而不是回调(不是解析的)结果。我认为您可以使用 async-await 来实现这一点。 这不是完整的代码。与上一部分一样,我需要调用异步函数,所以我使用作用域函数进行了调用,但您可以根据需要进行更改。

试试这样的:

const testTokenQuery = async (account_id, is_admin, query) => {
    pool.query(query, [account_id], function(err, result) {
        if(err) {
            return "invalid";
        } else {
            const bdd_account_id = String(JSON.stringify(result.rows[0].ac_account_id)).replace(/['"]+/g, '')
            const bdd_is_admin = String(JSON.stringify(result.rows[0].ac_isadmin)).replace(/['"]+/g, '')
            if (account_id == bdd_account_id || tok_is_admin == bdd_is_admin){
                return "valid";
            } else {
                return "invalid";
            }
        }
    });
}

const testToken = async (token) => {
    const checkTokenId_query = sql = fs.readFileSync('./sqlqueries/checkTokenId_query.sql').toString()
    const decodedToken = jwt.decode(token, 'JWT_SIGN_SECRET')
    const tok_account_id = decodedToken.account_id
    const tok_is_admin = decodedToken.isadmin
    
    return await testTokenQuery(tok_account_id, tok_is_admin, checkTokenId_query)
}

(async () => {
    const isvalid = await testToken('eyJhbGciO............ltJT0PhXCjV00')
    if(isvalid == "valid") {
        console.log("valid token")
    } else if(isvalid == "invalid") {
        console.log("not a valid token")
    } else {
        console.log("I don't know : " + isvalid) //======> Always the result with isvalid = undefined
    }
})();

【讨论】:

  • 响应仍然 ===> 未定义 ... = (((((
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 2020-10-12
  • 2017-03-18
  • 2016-01-16
  • 1970-01-01
相关资源
最近更新 更多