javascriptnode.jsibm-cloudibm-cloud-functions

IBM Cloud Function produce no output


I have some troubles while running this IBM Cloud Function:

    /**
  *
  * 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);
});

}

My problem is that the first invokes of this function (at least the first 3-4) produce no output. The subsequent calls run properly and the log is correctly shown. How can I fix this unpredictable behaviour? I'd like, of course, to retrieve my data at first call of this function. Thanks.


Solution

  • Node.js uses an non-blocking asynchronous programming model. This main function returns before the HTTP response is available.

    Returning a Promise will allow you to wait on the HTTP response.

    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 })
        });
    
      })
    }