Node.js Node JS-如何在异步函数中从查询中检索结果?

Node.js Node JS-如何在异步函数中从查询中检索结果?,node.js,sql-server,asynchronous,async-await,Node.js,Sql Server,Asynchronous,Async Await,节点js- 请帮我弄清楚如何在异步函数中从查询中检索值,好吗? 异步函数将以一个参数作为输入;sql结果应该是输出 我已经尝试了下面的代码,但它提供了“未定义”的结果。 我正在使用MSSQL数据库 任何提示都将不胜感激。 提前谢谢 getId('Justin') .then( (mydata)=>{ console.log(mydata) } ); //I hope it to display the id of 'Justin'. But instead, it returns unde

节点js- 请帮我弄清楚如何在异步函数中从查询中检索值,好吗? 异步函数将以一个参数作为输入;sql结果应该是输出

我已经尝试了下面的代码,但它提供了“未定义”的结果。 我正在使用MSSQL数据库

任何提示都将不胜感激。 提前谢谢

getId('Justin')
.then( (mydata)=>{ console.log(mydata) } ); //I hope it to display the id of 'Justin'. But instead, it returns undefined

async function getId(inputName){
    try{
        let pool = await sql.connect(config); //ok
        await pool.request()
        .input('inputName',   inputName )
        .query(  'select id from mytable where inputName = @inputName' , (err,result)=>{
            console.log (result.recordset[0].id); //here it works. it can display the id
            return result.recordset[0].id; // but I could not return the id from here.
        } )

    }
    catch(err){console.log(err)}
}

我们可以把它转换成一个承诺

Promise
对象表示异步操作的最终完成(或失败)及其结果值

function getId(inputName) {
 return new Promise(async (resolve, reject) {
  try {
   let pool = await sql.connect(config); //ok
   await pool.request()
    .input('inputName', inputName)
    .query('select id from mytable where inputName = @inputName', (err, result) => {
     return resolve(result.recordset[0].id); // return id from here
    })

  } catch (err) {
   reject(err)
  }
 })
}

getId('Justin')
 .then((mydata) => {
  console.log(mydata)
 });