0

I am writing a lambda function and returning a callback but the response is coming to be null.

My function looks like

var CloudmersiveValidateApiClient = require('cloudmersive-validate-api-client');
var defaultClient = CloudmersiveValidateApiClient.ApiClient.instance;

// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'API-KEY';

// Create an instance
var apiInstance = new CloudmersiveValidateApiClient.EmailApi();

exports.handler = async (event, context, callback) => {

    var email = event.email;

    apiInstance.emailFullValidation(email, callbackcm);

    var callbackcm = function(error, data, responsed) {

        if (error) {
            callback(null, {
               "Error": JSON.stringify(error)
           });
        } else {
            callback(null, {
               "Body": JSON.stringify(data)
           });
        }
    };

};

Is there something wrong with the way i am returning?

Nithin
  • 1,387
  • 4
  • 19
  • 48

1 Answers1

1

Your sequencing is wrong. You assign the callbackm function after you've passed it in as an argument. You either need to do:

exports.handler = async (event, context, callback) => {

    var email = event.email;

    var callbackcm = function(error, data, responsed) {
        // ....
    };

    apiInstance.emailFullValidation(email, callbackcm);

};

or do this:

exports.handler = async (event, context, callback) => {

    var email = event.email;

    apiInstance.emailFullValidation(email, callbackcm);    

    function callbackcm (error, data, responsed) {
        // ....
    };
};

This is because javascript parses code in two phases. Google "hoisting" for more on how this behaves.

slebetman
  • 109,858
  • 19
  • 140
  • 171
  • 1
    Also take a look at my answer to this other question for a more detailed exploration on corner cases: https://stackoverflow.com/questions/3887408/javascript-function-declaration-and-evaluation-order/3887590#3887590 – slebetman Dec 17 '18 at 09:39
  • Thank you so much. I'll have a look at it as well. – Nithin Dec 17 '18 at 09:58