对MySQL DB的Azure函数查询未等待查询结果

bmp9r5qi  于 2023-01-20  发布在  Mysql
关注(0)|答案(1)|浏览(121)

我有一个连接到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,但我不知道如何正确地使用它。

ar7v8xwq

ar7v8xwq1#

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?,是因为在分配变量时,控制台记录变量的语句在connection.query完成执行之前就执行了。
  • 现在,解决这个问题的方法是,所有与变量相关的处理(即查询结果)都必须在回调函数本身内部完成。
  • 这里我有一个NodeJS脚本,它将运行查询和console.log结果。
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();

输出:

你也可以在回调函数中为你的httptriggred函数设置context.res

相关问题