I am currently utilizing a lambda function within AWS to perform certain tasks, and it is essential for the function to retrieve some data from the AWS SSM resource in order to carry out its operations effectively. However, I am encountering difficulties in making the code wait for the call to getParameter
until the callback has been completed before proceeding.
I have experimented with organizing the code in two different ways.
Link to Structure Reference #1
Link to Structure Reference #2
Neither approach seems to successfully pause the execution as desired.
In my current implementation, which is based on "Structure reference #2", I am unsure of what mistake I might be making.
const aws = require('aws-sdk');
const crypto = require('crypto');
const ssm = new aws.SSM();
exports.handler = async (event, context, callback) => {
console.log(event.headers);
var webhook = JSON.parse(event.body);
var key = "";
var parameterRequest = ssm.getParameter( {
Name: "param1",
WithDecryption: true
}, function(err, data) {
if (err)
{
console.log(err);
}
else
{
key=data.Parameter.Value;
console.log(data);
}
});
await parameterRequest;
var hash = crypto.createHmac('sha1', key).update(JSON.stringify(webhook)).digest('hex');
console.log("HASH: sha1=" + hash);
console.log("Key:" + key);
}
const response = {
"statusCode": 200,
"statusDescription": "200 OK"
};
return callback(null, response);
Why are the
console.log("HASH: sha1=" + hash);
and console.log("Key:" + key);
statements being executed before console.log(data);
?
Update 7/2/2019
Await and Promise applied without the try-catch block:
const aws = require('aws-sdk');
const crypto = require('crypto');
const ssm = new aws.SSM();
exports.handler = async (event, context, callback) => {
console.log(event.headers);
var webhook = JSON.parse(event.body);
var key = "";
var parameterRequest = await ssm.getParameter( {
Name: "param1",
WithDecryption: true
}, function(err, data) {
if (err)
{
console.log(err);
}
else
{
key=data.Parameter.Value;
console.log(data);
}
}).promise();
var hash = crypto.createHmac('sha1', key).update(JSON.stringify(webhook)).digest('hex');
console.log("HASH: sha1=" + hash);
console.log("Key:" + key);
}
const response = {
"statusCode": 200,
"statusDescription": "200 OK"
};
return callback(null, response);