1

Node js - Please could you help me to figure out how to retrieve a value from a query, inside an async function? The async function will take one parameter as input; and the sql result should be the output.

I've tried the code below but it provides 'undefined' as a result. I'm using MSSQL db.

Any tips would be appreciated. Thanks in advance.

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)}
}

1 Answer 1

1

We can convert it into a Promise.

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

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)
 });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.