首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IBM函数不产生任何输出

IBM函数不产生任何输出
EN

Stack Overflow用户
提问于 2019-02-19 11:09:13
回答 2查看 397关注 0票数 2

在运行这个IBM函数时,我遇到了一些问题:

代码语言:javascript
复制
    /**
  *
  * 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)不会产生输出。随后的调用运行正常,日志显示正确。我怎样才能解决这种不可预测的行为呢?当然,我想在这个函数的第一次调用时检索我的数据。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-19 18:24:14

Node.js使用非阻塞异步编程模型.这个main函数在HTTP可用之前返回。

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

代码语言:javascript
复制
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 })
    });

  })
}
票数 3
EN

Stack Overflow用户

发布于 2020-07-04 16:34:13

另外还有两件事要检查:

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

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

代码语言:javascript
复制
async function main(params) {
  try {
    // some `await` function
  } catch (e) {
    // catch `await` errors
  }
}

module.exports = main;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54764871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档