从Node.js中Azure函数代码中的外部API调用获取响应

几天来,我一直在努力使Node.js中的Azure函数可以与外部API一起使用。我尝试使用.then以及Async Await模式等不同的组合和库,例如Axios或https,并且每次执行期间,我只会得到Promises作为回报。我想函数已执行,但是我在主函数中失去了它的上下文。 甚至执行以下简单示例:

module.exports = async function (context,req) {
context.log('Before the call');
let request_options = {
        method: 'GET',host: 'https://jsonplaceholder.typicode.com',path: '/todos/1',headers: {
            'Content-Type': 'application/json'
        }
};
require('http')
    .request(
         request_options,function (res,context) {
               context.log(res);
               context.log('I am within response');
         });
context.log('After the call');
};

结果:

2019-11-07T13:19:16.169 [Information] Executing 'Functions.Asyncawaittest' (Reason='This function was programmatically called via the host APIs.',Id=769ceae0-257f-432c-af8f-e35504ebc79a)
2019-11-07T13:19:20.880 [Information] Before the call
2019-11-07T13:19:20.881 [Information] After the call

这表示context.log上下文未处理响应。我无法调试响应中的代码吗?完全执行了吗? 我将处理一些嵌套的API调用,因此调试起来会变得更加复杂。

a68434576 回答:从Node.js中Azure函数代码中的外部API调用获取响应

实际上,与此同时,我使用node-red和ngrok设置了自己的API端点以将其公开,并发现它朝该方向触发。然后,我在Stackoverflow上发现了另一个相关问题,即将承诺与回调混合在一起。因此,我从model.exports函数声明中删除了“异步”,它现在可以正常工作,并且可以完美地调试日志。谢谢。

本文链接:https://www.f2er.com/3144453.html

大家都在问