我有一个连接到Azure外部的MySQL数据库的Azure函数。数据库连接正常,我能够运行INSERT查询,没有问题。问题是,当我尝试执行SELECT查询并尝试将返回的数据库记录打印到控制台时,它显示为未定义。以下是相关代码:
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 = 'tester@email.com'`;
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.');
connection.query调用中的日志会导致以下警告: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.
然后我尝试将结果保存到一个变量中,并在查询函数之后记录它,它返回为undefined
,我猜我使用了await wrong,但我不知道如何正确地使用它。
1条答案
按热度按时间ar7v8xwq1#
undefined
?,是因为在分配变量时,控制台记录变量的语句在connection.query
完成执行之前就执行了。console.log
结果。输出:
你也可以在回调函数中为你的httptriggred函数设置
context.res
。