Reputation: 387
I have an Azure Function that connects to a MySQL DB outside of Azure. The DB connection is working, I am able to run INSERT queries without issue. The problem is that when I try to do a SELECT query and try to print the returned DB records to the console it shows as undefined. Below is the relevant code:
const mysql = require('mysql');
module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
var connection = mysql.createConnection({
...
});
connection.connect();
let result;
const selectQuery = `SELECT * FROM emails WHERE email_address = '[email protected]'`;
await connection.query(selectQuery, async function (error, results, fields) {
if (error) throw error;
// This log doesn't work, it shows an error (see below code)
context.log(`Result: ${results}`)
result = results;
});
// Logging result here shows as undefined.
context.log(result);
connection.end();
context.log('Disconnected.');
The log inside the connection.query call results in this warning: Warning: Unexpected call to 'log' on the context object after function execution has completed. Please check for asynchronous calls that are not awaited or calls to 'done' made before function execution completes.
Then I try to save the result to a variable and log it after the query function, it returns as undefined
. My guess is that I'm using await wrong for this, but I can't figure out how to get it right.
Upvotes: 0
Views: 198
Reputation: 2069
Warning: Unexpected call to 'log' on the context
object after function execution has completed.
Please check for asynchronous calls that are not
awaited or calls to 'done' made before function
execution completes.
The reason for the above warning and why you get undefined
? is because when assigning the variable, the statements of console logging the variable are executed before the connection.query
can finish execution.
Now the work around for this would be that all the processing related to the variable i.e., result of the query must be done inside the call back function itself.
Here I have a NodeJS script which will run the query and console.log
the result.
var mysql = require('mysql');
var connection = mysql.createConnection({
...
});
connection.connect();
connection.query('SELECT L FROM NEWTABLE WHERE P=1 ', function (error, results, fields) {
console.log("Logging inside the callback function");
if (error) throw error;
console.log(results);
});
connection.end();
output:
you can also set the context.res
for your httptriggred function inside the callback function.
Upvotes: 1