Node.JS - Why is await not waiting

Viewed 861

I'm using a lambda function in AWS to do some work and I need the function get some data from the AWS SSM resource in order to complete the work. However I'm struggling to get the code to wait for the call to getParameter to wait until the call back has completed prior to moving on.

I've tried structuring the code in two different ways.

Structure reference #1

Structure reference #2

Neither way seems to get the execution to pause.

With my current implementation which is built on "Structure reference #2" I'm not sure what I'm doing wrong.

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 would the console.log("HASH: sha1=" + hash); and console.log("Key:" + key); get executed prior to the console.log(data);?

Update 7/2/2019

Await and Promise applied without the try catch:

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);
1 Answers

SSM.getParameter does not return Promise directly, it returns an AWS.Request. You can use AWS.Request.promise() to consume the request as a promise.

try {
    const data = await ssm.getParameter({
        Name: "param1",
        WithDecryption: true
    }).promise();
    console.log(data);

    const key = data.Parameter.Value;
} catch (err) {
    console.log(err);
}
Related