【问题标题】:Cloud Function stops responding on random external API callsCloud Function 停止响应随机外部 API 调用
【发布时间】:2019-10-09 12:05:46
【问题描述】:

您好,我正在开发一个使用云功能的应用程序。所以问题是我正在使用 Blaze 订阅,并且我正在对 AWS / Azure 服务器进行多个 API 调用。这些电话大部分时间都不会得到解决,执行就会停止。停止我的意思不是超时或什么,停止我的意思是无限期地停止,我不会收到任何错误或超时。它只会停止工作和响应

问题是它在本地模拟器上运行良好,但只要我在服务器上对其进行测试,它就会出现这种行为。

我在尝试对函数进行异步调用时可能遗漏了什么?

有什么帮助吗?

这是代码的主要逻辑: index.js

APIEngine.initialize(payload)
          .then(async result => {
            new ResourceEngine(result, payload)
              .getResourceFromRegions()
              .then(resources => {
                console.log("signature resources: ", resources);
                //     new ScanEngine(
                //       resources.apiEngine,
                //       resources.response,
                //       payload.report
                //     ).run();
              })
              .catch(err => {
                console.log("error ===>", err);
              });
          })
          .catch(err => {
            return console.log("ERROR ====>", err);
          });

【问题讨论】:

  • 转到此 Cloud Function 的 Stackdriver Logging 并检查您是否在异步调用的“.then”块中的 console.log 之前收到“Function execution takes x ms”日志。如果是这种情况,您的云函数会在异步调用之前终止,
  • @Monroe 是的,function terminated 确实出现在 console.log 的 then 之前,但问题是有时它也会完全执行

标签: node.js firebase google-cloud-platform async-await google-cloud-functions


【解决方案1】:

如果您在云函数中发出异步 HTTP 请求,并且在执行异步块之前在 Stackdriver Logging 中收到 函数终止 日志,这意味着您没有很好地管理您的函数的生命周期,您需要对代码进行更改以避免调用未解决的问题。

您需要在异步调用完成时通知该函数。

如果你的函数是一个 HTTP 函数 (https://cloud.google.com/functions/docs/writing/http) 你只需要在收到你的 promise => res.status(200).send("OK") 的响应时响应 200 OK块。

如果您的函数是后台函数 (https://cloud.google.com/functions/docs/writing/background),您需要使用“return”将承诺返回给函数

例子:

return APIEngine.initialize(payload)
      .then(async result => {
        new ResourceEngine(result, payload)
          .getResourceFromRegions()
          .then(resources => {
            console.log("signature resources: ", resources);
            //     new ScanEngine(
            //       resources.apiEngine,
            //       resources.response,
            //       payload.report
            //     ).run();
          })
          .catch(err => {
            console.log("error ===>", err);
          });
      })
      .catch(err => {
        return console.log("ERROR ====>", err);
      });

【讨论】:

  • 感谢@Sebastian 的快速回答。我会试试这个,让你们知道它是否有效。
  • 在代码中进行了这些更改以处理Async / Await 模式。 ``` let apiEngineRef = await APIEngine.initialize(payload) if (apiEngineRef) { // 调用资源引擎 let getAllResources = await ResourceEngine.getResourceFromRegions(apiEngineRef.apiEngine, payload) console.log('getAllResources: ', getAllResources); } if(getAllResources) { // 立即运行扫描引擎 } ```
猜你喜欢
  • 2019-01-06
  • 1970-01-01
  • 2019-10-09
  • 2022-11-18
  • 1970-01-01
  • 2015-05-05
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多