I am have an function that executes sql stored procedure. By itself, function works as expected. When I call that function from node.js route async/await doesn't wait for a return value. Relevant code is below:
router.post('/new_item', async (req, res)=> {
try {
let sp_name = req.body.sp_name;
let sp_params = req.body.sp_params;
let sql_sp_call_status = 'in-progress'
sql_sp_call_status = await sql_sp_execute(sp_name, sp_params)
console.log('2- ' + sql_sp_call_status)
} catch (err) {
res.status(500)
console.log(err)
res.send(err.message)
}
res.json('done')
})
-----------
async function sql_sp_execute(sp_name, sp_params){
const pool = await poolPromise
const req = await pool.request();
await sp_params.forEach(function(param) {
let ptype1 = sql.TYPES[param.type]
req.input(param.name, ptype1, param.value);
});
await req.execute(sp_name, (err, recordset) => {
if (err) {
console.log(err)
return 'sql_call_failed'
}else{
console.log( '1-success')
return 'sq_sp_call_success';
}
});
}
I expect to see in the console :
1-success
2-sq_sp_call_succes
But it looks like this:
2- undefined
POST /.../new_item 200 1.300 ms - 6
1- success
You are using the keyword await
on a callback expression, so it won't behave as you expect.
await req.execute(sp_name, (err, recordset) => {...}) // awaiting a callback expression
One thing you could do is use the function promisify
exported in Node's util
module.
const { promisify } = require('util')
// ...
const recordset = await promisify(req.execute.bind(req))(sp_name) // now node will wait
// note: err is thrown if it errors