Francesco_Lastrino
Francesco_Lastrino

Reputation: 45

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.

Upvotes: 2

Views: 477

Answers (2)

Andi
Andi

Reputation: 3727

Two additional things to check:

  1. Make sure to append .json to your endpoint
  • Example: https://<ibm-domain>/api/v1/web/<username>/default/<function>.json
  1. Make sure to select Enable as Web Action in the Endpoints sidebar menu.

Also, you should be able to return an async main function in lieu of the Promise object.

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

module.exports = main;

Upvotes: 0

James Thomas
James Thomas

Reputation: 4339

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

  })
}

Upvotes: 3

Related Questions