简体   繁体   English

Javascript,返回主函数时出错

[英]Javascript, error when return on a main function

I have my function who call the DB to do something :我有我的函数调用数据库做某事:

function callQuery(query) {
  db.query(query, (err, res) => {
    if (err) {
      // Error DB connecion
      console.log(err.stack)
    } else {
      // Send back the results
      return(res.rows[0])
    }
  })
}

My problem is when I call this function by :我的问题是当我通过以下方式调用此函数时:

const idUser = callQuery("INSERT INTO blablabla RETURNING *")

My data is successfully added in the DB, but idUser came null.我的数据已成功添加到数据库中,但 idUser 为空。 It should be res.rows[0]它应该是 res.rows[0]

I am using this tutorial (who instead of setting a variable, call console.log) : https://node-postgres.com/features/connecting我正在使用本教程(而不是设置变量,而是调用 console.log): https : //node-postgres.com/features/connecting

Thank you in advance先感谢您

I think this is something due to asynchronous我认为这是由于异步

let promisess = new Promise(function(resolve, reject) {
function callQuery(query) {
  db.query(query, (err, res) => {
    if (err) {
      // Error DB connecion
      console.log(err.stack)
    } else {
      // Send back the results
      resolve(res.rows[0])
    }
  })
}
});
promisess.then((res)=> {
your data in res
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM