0
const AWS = require('aws-sdk');

exports.handler = (event) => {
    AWS.config.update({region: 'eu-west-1'});
    var cw = new AWS.CloudWatch({apiVersion: '2010-08-01'});

    var alarmStatus = {};
    cw.describeAlarms({}, function(err, data) {
        if (err) {
            console.log("Error", err);
        } else {
            data.MetricAlarms.forEach(function (item, index, array) {
                var pair = {[item.AlarmName]: item.StateValue};
                alarmStatus = {...alarmStatus, ...pair};
                console.log(alarmStatus);
            });
        }
    });

    const response = {
        statusCode: 200,
        body: JSON.stringify(alarmStatus),
    };
    return response;
};

I want to send response back to the caller of the lambda function, but since describe alarm function of cloudwatch is asynchronous, I am getting empty response in the body. How can I wait for the function to execute before returning the response?

4
  • Is it perhaps an option to add an obserable for alarmStatus? If the value changed, return the response. Commented Mar 7, 2019 at 12:56
  • why not put response in the else part of the describeAlarms? Commented Mar 7, 2019 at 13:28
  • @Mahendrasuthar Putting response in else part is sending null in response. I guess, we can't have return statement inside the callback. I am not sure about that. In my case it is not working Commented Mar 7, 2019 at 13:33
  • async would be a great choice here..more info @ caolan.github.io/async Commented Mar 7, 2019 at 13:47

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.