问题描述

开发 Azure JS Function(NodeJS),使用 mssql 组件操作数据库。当SQL语句执行完成后,在Callback函数中执行日志输出 context.log(" ...") , 遇见如下错误:

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.

Function name: HttpTrigger1. Invocation Id: e8c69eb5-fcbc-451c-8ee6-c130ba86c0e9. Learn more: https://go.microsoft.com/fwlink/?linkid=2097909

错误截图

问题解答

JS 函数代码(日志无法正常输出)

var sql = require('mssql');
var config = {
user: 'username',
password: 'Password',
server: '<server name>.database.chinacloudapi.cn', // You can use 'localhost\\instance' to connect to named instance
database: 'db name', options: {
encrypt: true // Use this if you're on Windows Azure
}
}

module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.'); await callDBtoOutput(context); context.log('################');
//Default Code ...
const name = (req.query.name || (req.body && req.body.name));
const responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."; context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
} async function callDBtoOutput(context) {
try {
context.log("Some Message from callDBtoOutput") var ps = new sql.PreparedStatement(await sql.connect(config))
await ps.prepare('SELECT SUSER_SNAME() ', async function (err) {
if (err) {
context.log(err)
}
context.log("start to exec sql ...from callDBtoOutput")
await ps.execute({}, async function (err, recordset) {
// ... error checks
context.log(recordset)
context.log("Login SQL DB successfully....from callDBtoOutput")
ps.unprepare(function (err) {
// ... error checks
});
});
});
} catch (error) {
context.log(`Some Error Log: from callDBtoOutput`, error);
}
}

在 callDBtoOutput() 函数中,调用sql prepare 和 execute方法执行sql语句,虽然已经使用了async和await关键字,但根据测试结果表明:Function的主线程并不会等待callback函数执行。当主线程中context对象释放后,子线程中继续执行context.log函数时就会遇见以上警告信息。

为了解决以上prepare和execute方法中日志输出问题,需要使用其他执行sql的方法。在查看mssql的官方说明(https://www.npmjs.com/package/mssql#query-command-callback)后,发现query方法能够满足要求。

query (command, [callback])

Execute the SQL command. To execute commands like create procedure or if you plan to work with local temporary tables, use batch instead.

Arguments

  • command - T-SQL command to be executed.
  • callback(err, recordset) - A callback which is called after execution has completed, or an error has occurred. Optional. If omitted, returns Promise.

经过多次测试,以下代码能完整输出Function过程中产生的日志。

JS 函数执行SQL代码(日志正常输出)

var sql = require('mssql');

var config = {
user: 'username',
password: 'Password',
server: '<server name>.database.chinacloudapi.cn', // You can use 'localhost\\instance' to connect to named instance
database: 'db name', options: {
encrypt: true // Use this if you're on Windows Azure
}
} module.exports = async function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.'); // context.log('call callDBtoOutput 1');
// await callDBtoOutput(context); //context.log('call callDBtoOutput 2');
await callDBtoOutput2(context); context.log('################');
const name = (req.query.name || (req.body && req.body.name));
const responseMessage = name
? "Hello, " + name + ". This HTTP triggered function executed successfully."
: "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."; context.res = {
// status: 200, /* Defaults to 200 */
body: responseMessage
};
} async function callDBtoOutput2(context) {
context.log("1: Call SQL Exec function ....")
await sql.connect(config).then(async function () {
// Query
context.log("2: start to exec sql ... ")
await new sql.Request().query('SELECT SUSER_SNAME() ').then(async function (recordset) {
context.log("3: Login SQL DB successfully.... show the Query result")
context.log(recordset); }).catch(function (err) {
// ... error checks
});
})
context.log("4: exec sql completed ... ")
}

结果展示(完整日志输出)

参考资料

node-mssql: https://www.npmjs.com/package/mssql

context.done : https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node?pivots=nodejs-model-v3&tabs=javascript%2Cwindows-setting-the-node-version#contextdone

The context.done method is deprecated

Now, it's recommended to remove the call to context.done() and mark your function as async so that it returns a promise (even if you don't await anything).

【Azure 应用服务】Azure JS Function 异步方法中日志无法输出问题引发的(await\async)关键字问题的更多相关文章

  1. 【Azure 应用服务】Azure Function集成虚拟网络,设置被同在虚拟网络中的Storage Account触发,遇见Function无法触发的问题

    一切为了安全,所有的云上资源如支持内网资源访问,则都可以加入虚拟网络 问题描述 使用Azure Function处理Storage Account中Blob 新增,更新,删除等情况.Storage A ...

  2. 【Azure 应用服务】App Service .NET Core项目在Program.cs中自定义添加的logger.LogInformation,部署到App Service上后日志不显示Log Stream中的问题

    问题描述 在.Net Core 5.0 项目中,添加 Microsoft.Extensions.Logging.AzureAppServices 和 Microsoft.Extensions.Logg ...

  3. 【Azure 应用服务】部署Kafka Trigger Function到Azure Function服务中,解决自定义域名解析难题

    问题描述 经过前两篇文章,分别使用VM搭建了Kafka服务,创建了Azure Function项目,并且都在本地运行成功. [Azure Developer]在Azure VM (Windows) 中 ...

  4. 【Azure 应用服务】App Service/Azure Function的出站连接过多而引起了SNAT端口耗尽,导致一些新的请求出现超时错误(Timeout)

    问题描述 当需要在应用中有大量的出站连接时候,就会涉及到SNAT(源地址网络转换)耗尽的问题.而通过Azure App Service/Function的默认监控指标图表中,却没有可以直接查看到SNA ...

  5. 【Azure 应用服务】Azure Function App使用SendGrid发送邮件遇见异常消息The operation was canceled,分析源码逐步最终源端

    问题描述 在使用Azure Function App的SendGrid Binging功能,调用SendGrid服务器发送邮件功能时,有时候遇见间歇性,偶发性异常.在重新触发SendGrid部分的Fu ...

  6. 【Azure 应用服务】App Service For Linux 如何在 Web 应用实例上住抓取网络日志

    问题描述 在App Service For Windows的环境中,我们可以通过ArmClient 工具发送POST请求在Web应用的实例中抓取网络日志,但是在App Service For Linu ...

  7. 【Azure 应用服务】App Service For Linux 部署Java Spring Boot应用后,查看日志文件时的疑惑

    编写Java Spring Boot应用,通过配置logging.path路径把日志输出在指定的文件夹中. 第一步:通过VS Code创建一个空的Spring Boot项目 第二步:在applicat ...

  8. 【Azure Developer】在Github Action中使用Azure/functions-container-action@v1配置Function App并成功部署Function Image

    问题描述 使用Github Action,通过 Azure/functions-container-action@v1 插件来完成 yaml 文件的配置,并成功部署Function Image 的过程 ...

  9. Azure 应用服务中的 API 应用、ASP.NET 和 Swagger 入门

    学习内容: 如何通过 Visual Studio 2015 中的内置工具在 Azure 应用服务中创建和部署 API 应用. 如何使用 Swashbuckle NuGet 包动态生成 Swagger ...

  10. 【Azure 应用服务】App Service中,为Java应用配置自定义错误页面,禁用DELETE, PUT方法

    问题定义 使用Azure应用服务(App Service),部署Java应用,使用Tomcat容器,如何自定义错误页面呢?同时禁用DELETE, PUT方法 解决办法 如何自定义错误页面呢?需要在 J ...

随机推荐

  1. Typora安装及MarkDown语法使用

    Typora下载及安装 1.百度直接搜索Typora,第一个词条点进去 2.进入之后点击Download 3.选择操作系统,因为我的是windows,所以我选择windows版本进行下载 4.根据自己 ...

  2. java中的4种引用和GC Roots

    https://juejin.im/post/5d06de9d51882559ee6f4212?utm_source=gold_browser_extension 1.首先,四种引用如下: Final ...

  3. 我在迁移我的IDEA的项目、模块等东西的过程中发生过的一部分问题的我的一部分的记录以及我的解决方案如下

    使用idea2019阶段报的一些错: 1.'xxxServlet' is not assignable to 'javax.servlet.Servlet' 解决方案:把tomcat加入classpt ...

  4. 在Windows上访问linux的共享文件夹

    1. https://blog.csdn.net/weixin_44147924/article/details/123692155

  5. arpspoof、driftnet工具使用

    一.arpspoof.driftnet工具安装: 在kali liux中: 安装命令:apt install dsniff      apt install driftnet 二.使用arpspoof ...

  6. mysql 排序ROW_NUMBER() RANK() DENSE_RANK()

    with 月业绩 as (SELECT 年份,月份, ROUND(sum(总业绩)/100000) 业绩 FROM `myj` group by 年份,月份) select * ,ROW_NUMBER ...

  7. Matlab - 在Figure界面去掉图像的坐标刻度

    Matlab版本:2018b 经过一番尝试,发现有两种方法 第一种:修改坐标轴的Visible属性,去掉坐标轴数字和坐标轴标签 第二种:删除Tick,只去掉坐标轴数字 第一种 ①原图 ②如果有多个子图 ...

  8. 看图就会-网络攻击 (xss和csrf)

    最近发现好多东西整理过后就没啥印象,但是思维导图很好用,能取其精华去其糟粕

  9. RTE NG-Lab:一起探索下一代实时互动新世界

    互联网已经彻底改变了我们的工作和生活.从纸书信笺,到智能手机中的 App,再到 VR 头显,实时互动体验逐代升级,已经成为了我们生活的一部分.随着元宇宙的爆火,新增的实时互动场景日益颠覆着我们的想象力 ...

  10. 重学c#系列—— explicit、implicit与operator[三十四]

    前言 我们都知道operator 可以对我们的操作符进行重写,那么explicit 和 implicit 就是对转换的重写. 正文 explicit 就是强制转换,然后implicit 就是隐式转换. ...