I'm using the below code as a lambda function executed on an API call.
The issue I'm having is when the response
and callback
are in their current position the array scans
returns []
even though a scan object is populated and pushed to the array. However when response
and callback
are placed in ***PLACEHOLDER***
section, the array returns populated with the scan object.
I understand this has something to do with the asynchronous nature of the code as I have looked at many similar questions on stack but alongside the AWS-SDK code I can't figure out what to do to correct it.
const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient();
const iot = new AWS.Iot;
exports.handler = (event, context, callback) => {
iot.listThings(null, function(err, data) {
var scans = [];
if (err) {
callback(err, null);
}
else {
for (var i = 0; i < data.things.length; i++) {
var device = data.things[i].attributes;
const params = {
// redacted
};
ddb.query(params, function(err, data) {
if (err) {
callback(err, null);
}
else {
var scan = {
"area": device.area,
"count": data["Count"]
};
scans.push(scan);
// ***PLACEHOLDER***
}
});
}
}
var response = {
"statusCode": 200,
"headers": {},
"body": JSON.stringify(scans),
"isBase64Encoded": false
};
callback(null, response);
});
};