【问题标题】:Azure Function - js - not running correctly, but no error in the logsAzure Function - js - 运行不正确,但日志中没有错误
【发布时间】:2019-02-10 06:16:16
【问题描述】:

我正在尝试构建一个函数来从我的 IoTHub 获取数据并通过 GET 将数据发送到我的 Web 服务。

这就是我的功能:

var http = require('https');
module.exports = function (context, IoTHubMessages) {

    IoTHubMessages.forEach(message => {
        // context.log(`Processing message9: ${JSON.stringify(message)}`);
        console.log(`what the what???`);
        let url = `<my site in Azure>.azurewebsites.net`;
        console.log(url);
        let path = "/sensor/" + message.d1 + "/" + message.d2 + "/" + message.d3 + "/";
        console.log(path);
        var req = http.request({
            host: url,
            path: path,
            method: 'GET'
        });
        req.on('error', function(e) {
            console.log('problem with request: ' + e.message);
        });
        req.on('end', function(e) {
            console.log('finished with request');
        });

        req.end();
    });

    context.done();
};

日志如下所示:

2019-02-10T06:06:22.503 [Information] Executing 'Functions.IoTHub_EventHub1' (Reason='', Id=ea6109b0-5037-4f15-9efc-845222c6f404)
2019-02-10T06:06:22.512 [Information] Executed 'Functions.IoTHub_EventHub1' (Succeeded, Id=ea6109b0-5037-4f15-9efc-845222c6f404)
2019-02-10T06:06:22.786 [Information] Executing 'Functions.IoTHub_EventHub1' (Reason='', Id=f344c44f-a6ff-49b3-badb-58429b3476dc)
2019-02-10T06:06:22.796 [Information] Executed 'Functions.IoTHub_EventHub1' (Succeeded, Id=f344c44f-a6ff-49b3-badb-58429b3476dc)

如果我取消注释这一行:

context.log(`Processing message9: ${JSON.stringify(message)}`);

然后在日志输出中显示 JSON 数据。在 Executing 和 Executed 对之间,我看到:

2019-02-10T05:59:28.906 [Information] Processing message9: {"topic":"iot","d1":"200","d2":"200","d3":"200"}
  • 我没有收到我的 GET 请求
  • 在初始字符串化行之后我没有看到 console.log 消息
  • 我没有看到任何错误。

我尝试了不同的引号来查看 Node 是否更喜欢其中一个。

有时在重新启动函数时,我会在日志中看到类似这样的消息,但由于日志中有我的 JSON 字符串而忽略了它

2019-02-10T06:00:10.600 [Error] Executed 'Functions.IoTHub_EventHub1' (Failed, Id=2b3959cd-5014-4c50-89a3-77e37f2a890e)

Binding parameters to complex objects (such as 'Object') uses Json.NET serialization. 
1. Bind the parameter type as 'string' instead of 'Object' to get the raw values and avoid JSON deserialization, or
2. Change the queue payload to be valid json. The JSON parser failed:
Unexpected character encountered while parsing value: T. Path '', line 0, position 0.

【问题讨论】:

  • 也许从用context.log 替换5 console.log 开始?
  • 您可能会在请求完成之前致电context.done。在调用context.done 之后,函数执行应该结束,因此您不会看到更多日志,但您将继续处理事件循环中剩下的任何内容。我会尝试删除现有的context.done 调用并将其替换为添加req.end 的全局计数器和匹配if(counter === IoTHubMessages.length) {context.done();} 时的退出条件。另一方面,为了提高性能,您可能希望使用 keepAlive:true nodejs.org/api/http.html#http_new_agent_options 传递代理
  • @Stock Overflaw - 根据肌肉记忆编写控制台 - 甚至没有注意到它是有效的上下文。
  • 肌肉被高估了:耐心和新鲜的眼睛比暴力和愤怒更重要,正如一些死去已久的诗人所说。那你的问题就解决了吗? (因为,好吧,你的代码从这里看起来没问题,除了@nelak 提出的观点:如果你想在req 的听众中做某事,你的context.done 可能被调用得太早)
  • @StockOverflaw 我更改为 .C#,它按预期工作。在这样做之前,我在这里尝试了各种建议,但没有成功。

标签: javascript node.js azure azure-functions


【解决方案1】:

这里的问题是forEach循环不是在调用context.done之前等待结果的循环

@nelak 在他的评论中指出的那样发生这种情况时,azure 函数会停止并且不会发生其他任何事情。

请注意以下事项。我决定用一个简单的setTimeout 函数替换http 库,但这或多或少是一样的。您的代码发生了什么,在下一个 sn-p 中进行了说明,请注意调用 console.log 的顺序。

const myFn = function (context, IoTHubMessages) {
    IoTHubMessages.forEach(message => {
        console.log('inside foreach!')
        setTimeout(() => {
            console.log('inside settimeout, this is when your request is answered!')
        }, 1)
    });

    console.log('outside all!')
};

myFn(null, [0, 1])

如果你放弃了不同的行为,你可以用async-await 模式重写它,然后它看起来是同步的,但实际上是异步的。

var callIt = () => {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('inside settimeout!')
            return resolve('ok')
        }, 1)
    })
}
var myFnAwait = async (context, IoTHubMessages) => {
    for (i of IoTHubMessages){
        console.log('before settimeout')
        await callIt()
        console.log('after timeout')
    }

    console.log('outside all!')
};

myFnAwait(null, [0, 1])

【讨论】:

    猜你喜欢
    • 2015-05-11
    • 2018-05-08
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多