问题
The following code is for an Azure Function (Serverless) Http endpoint. The code uses the Tedious NPM package for connecting to an Azure SQL database.
The challenge I am having, is understanding how to properly return the results from the callback behavior prior to the function exiting. Ideally, I'd like to do all my SQL work done synchronously in-line, without the callback behavior, but I understand that may not be best practice.
Can anyone explain how this code could be modified to better demonstrate the right way to return the SQL/Tedious callback results so they are delivered to the JSON output?
const { Connection, Request } = require('tedious');
require('dotenv').config();
module.exports = async function (context, req) {
try {
const config = { /* redacted for brevity */ };
let connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
context.log('Error: ', err);
}
const request = new Request(
`SELECT TOP 10 Id, Username FROM Users`,
(err, rowCount, rows) => {
if (err) {
console.error(err.message);
} else {
console.log(`${rowCount} row(s) returned`);
// this object does not render in output (called after context.log outside callback)
context.res.status(200).json({ data: 'ok' });
}
}
);
connection.execSql(request);
});
// This line is hit before the callback is called
// There is no response sent back to the browser
context.log('Hey, I ran before the callback...');
} catch (error) {
context.log('error occurred ', error);
context.res.status(500).send(error);
}
};
Update Should anyone else stumble upon this post, I switched to using the 'mssql' node package, and this works as expected for me. Note the connectionstring has to have ?encrypt=true per the package documentation.
I would still like to know what was wrong with the original code if possible.
const sql = require('mssql');
require('dotenv').config();
module.exports = async function (context, req) {
try {
await sql.connect(process.env.AZURE_SQL_CONNECTIONSTRING);
const result = await sql.query`select Id, Username from Users`;
context.res.status(200).send(result);
} catch (error) {
context.log('error occurred ', error);
context.res.status(500).send(error);
}
};
来源:https://stackoverflow.com/questions/62233383/understanding-js-callbacks-w-azure-functions-tedious-sql