12
votes

This is the code running in an aws lambda function.

exports.handler = (event, context, callback) => {
            // TODO implement

          mqfunc1(func2);



};
var func2 = function(data) {
            console.log('got data: '+data);

};
var mqfunc1 = function(callback) {
        var myCallback = function(data) {
        console.log('got data: '+data);
        };

        var usingItNow = function(callback) {
        callback('get it?');
        };

};

Now I do get the the message which i want to print in the console. But I want to show the same message printed in the console using the callback function inside exports.handler.

I tried using callback function using various ways inside exports.handler but I am always getting null. I do understand that in a node js scripts all the function calls are asynchronous, so how do I return a value from any function and callback the same inside exports.handler, i.e. display the same in Execution result.

2
Can you add a sample output of what you are expecting.gvmani

2 Answers

22
votes

That was the old version of lambda i.e for Node.js runtime v0.10.42. The new AWS version callback has two arguments i.e for Node.js runtime v4.3 or v6.10

callback(response_error, response_success)

module.exports.publisher = (event, context, callback) => 
{
   callback(response_error, response_success)
}

I tend to pass a status code, in case I want to use the result after my job is done:

const response_success = {
      statusCode: 200,
      body: JSON.stringify({
        message: 'ok'
      }),
};

const response_error = {
    statusCode: 400,
    body: JSON.stringify({
        message: 'error'
    }),
};

if (error) {
   callback(response_error)
} else {
   callback(undefined, response_success)
}

Reference: http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

5
votes

You should call the callback function itself — the one passed as an argument to exports.handler.

E.g.:

exports.handler = (event, context, callback) => {
      mqfunc1(callback);
};

var mqfunc1 = function(callback) {
    callback({'result': 'success'});
};