IBM Cloud Function 不产生任何输出

IBM Cloud Function produce no output

我在运行使用这个 IBM Cloud 功能时遇到了一些麻烦:

    /**
  *
  * main() will be run when you invoke this action
  *
  * @param Cloud Functions actions accept a single parameter, which must be a JSON object.
  *
  * @return The output of this action, which must be a JSON object.
  *
  */

function main(params) {

    const https = require('https');

https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data).explanation);
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});

}

我的问题是此函数的第一次调用(至少前 3-4 次)没有产生输出。后续调用 运行 正确并且日志正确显示。我该如何解决这种不可预测的行为?当然,我希望在第一次调用此函数时检索我的数据。谢谢

Node.js 使用非阻塞异步编程模型。此 main 函数 returns 在 HTTP 响应可用之前。

返回 Promise 将允许您等待 HTTP 响应。

function main(params) {
  return new Promise((resolve, reject) => {
    const https = require('https');

    https.get('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', (resp) => {
      let data = '';

      // A chunk of data has been recieved.
      resp.on('data', (chunk) => {
        data += chunk;
      });

      // The whole response has been received. Print out the result.
      resp.on('end', () => {
        const explanation = JSON.parse(data).explanation
        console.log(explanation);

        resolve({ explanation })
      });

    }).on("error", (err) => {
      console.log("Error: " + err.message);
      reject({ error: err.message })
    });

  })
}

另外两件事要检查:

  1. 确保将 .json 附加到您的端点
  • 示例:https://<ibm-domain>/api/v1/web/<username>/default/<function>.json
  1. 确保在 Endpoints 侧边栏菜单中 select Enable as Web Action

此外,您应该能够 return 一个 async 主函数来代替 Promise 对象。

async function main(params) {
  try {
    // some `await` function
  } catch (e) {
    // catch `await` errors
  }
}

module.exports = main;