0

I am using the mssql npm library which is working, but I am struggling to get the recordset returned from the sub-level callback.

How do I get the recordset back when it's multiple layers of callback?

let storedRecordset = await doQuery();

async function doQuery(){

     let recordset;

     const ps = new sql.PreparedStatement(/* [pool] */)
     ps.input('param', sql.Int)
     ps.prepare('select @param as value', err => {
         // ... error checks

         ps.execute({param: 12345}, (err, result) => {
             // ... error checks
 
             recordset = result;        
     
             // release the connection after queries are executed
             ps.unprepare(err => {
                 // ... error checks

                 return recordset;

             })
         })
     })

}

Thanks

Ash
  • 62
  • 7
  • 1
    Basically, stop using plain asynchronous callbacks and convert to a promise-based control flow. That provides a straight-forward mechanism for propagating back results or an error. Either find and use the promise interfaces that already exist for the libraries you're using or promisify the APIs you are using so you can do your entire control flow using promises. – jfriend00 Feb 02 '23 at 23:35

1 Answers1

1
let storedRecordset = await doQuery();

function doQuery() {
  return new Promise((r) => {
    let recordset;

    const ps = new sql.PreparedStatement(/* [pool] */);
    ps.input("param", sql.Int);
    ps.prepare("select @param as value", (err) => {
      // ... error checks

      ps.execute({ param: 12345 }, (err, result) => {
        // ... error checks

        recordset = result;

        // release the connection after queries are executed
        ps.unprepare((err) => {
          // ... error checks

          r(recordset);
        });
      });
    });
  });
}
Konrad
  • 21,590
  • 4
  • 28
  • 64