The curious case of Node.JS: The mysterious behaviour of await not waiting

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

Answer №1

SSM.getParameter function doesn't directly return a Promise, instead it returns an AWS.Request. You can utilize AWS.Request.promise() to handle 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);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a unique Vue.js modal window for every individual product

Currently, I am in the process of creating a small online store using Vue.js. Within this store, I have a variety of products each with unique names and prices. In order to provide more information about each product, I have included a "Details" button. M ...

Acquire JSON data from a URL and display it on the webpage

I'm facing an issue where the JSON data I'm trying to fetch from a URL is not displaying due to an uncaught reference error in my code. How can I modify the code to ensure that the data gets shown? var url = "https://fantasy.premierleague.com/ ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...

Showcasing solely the latest entry in the database utilizing nodeJS

I am having an issue with my code where it is only displaying the last record from the database. How can I modify it to display all the records from the database using nodeJS? Any assistance would be greatly appreciated. Thank you. var express = require ...

The writeToDB function is triggered only one time

I've encountered an issue with my node.js code where the writeToDB function is being called, but data is not inserted in the database after the first time. Can someone help me understand why? uploadInfoObject = { ProcessId: pid, Type: "type", ...

Development of a chart application involving frontend and backend components, utilizing chartjs for data visualization, mongodb for storage

As a beginner in generating charts using the ajax mechanism and chartjs, I've encountered an issue where the graphs are being plotted incorrectly. Any guidance on how to improve would be greatly appreciated. Thank you! Here is my JavaScript code for ...

What is the process for getting involved with npm commands?

Here is an excerpt from my package.json file: "scripts": { "cpFile": cp ../template/index.js /src/view/home/ } When I try to run the command: npm run cpFile fileName.js I expect it to execute: cp ../template/index.js /src/view/home/fileName.js How ...

Can the arrangement of icons/buttons on the JW Player control bar be customized?

I am trying to customize the skin of my JWplayer like this: This is my current progress: I have been researching how to rearrange the order of icon / button on the controlbar. According to the jwplayer documentation, the buttons on the controlbar are div ...

Ensure Focus Retention Upon Clicking Inside Iframe with li a:focus

How can I prevent my ul.SideNav_Main li a:focus class from losing focus when I click on the iframe or elsewhere on the page? Shouldn't it maintain focus until I click on another URL in the list? Is it possible to solve this issue with just CSS, or wo ...

A controller in Angular.js that leverages several different services

I'm having trouble injecting multiple services into a controller. Here are my listed files: index.html file: <script src="'./angular/angular.min.js'></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Codeigniter dilemma: Unable to upload images using Summernote

Summernote has been successfully integrated into my website (which is built using Codeigniter). Text editing functions work perfectly fine, however, I'm facing an issue with image uploads. When uploading images, Summernote reads them as base64. This ...

What steps can be taken to verify if the user has transmitted a JSON Web Token?

Recently started using Express and been struggling with this particular error for quite a while. const token=req.header("jwt") console.log(token) if(!token ){ return res.json('no jwt') console.log('nojw ...

Get names with specific characteristics by using a Javascript object that acts as an associative array

Can someone help me with my code? I'm trying to create an input box that, when I type in "A", will display the names of students who have earned "A" grades. I feel like I'm close to getting it right, but there's something missing. Any assist ...

The functionality of Angular is not compatible with a mobile network connection

Recently, I noticed that my Angular 6 application hosted on my server with SSL and HTTPS protocol loads quickly on my computer but is extremely slow on my mobile phone, taking about 3-4 minutes to fully load. I conducted network profiling using Chrome, bu ...

The call stack size has been exceeded, even after removing node_modules and package-lock.json and attempting to run 'npm i'

Sorry for repeating the 'maximum call stack size exceeded' issue, but I've exhausted almost every suggestion on stackoverflow. Versions: node v.14.19.0 npm v.6.14.16 Here is the error log: > <a href="/cdn-cgi/l/email-protection" clas ...

Shut down jquery modal

I have successfully imported Jquery Modal using the following two links (js and css) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cl ...

The method of iterating over a string in key-value pairs

How can I efficiently loop through a string and extract key/value pairs? The data is provided to me as a single string using the jstorage plugin. I attempted to split the string into an array, but the resulting key/values were not as expected. For exampl ...

Retrieving JSON data using AJAX while incorporating NgTable settings

I'm currently facing an issue with sorting and filtering data in ngTables using an AJAX call. Although I have managed to display the data using ng-repeat, the sorting functions do not work as expected. After referencing this example http://plnkr.co/ed ...

Payload bytes do not match the expected byte values

I am facing an issue where the image data sent by the user is getting saved on the server in a corrupt state. Here is the structure of my setup: - api . index.js - methods . users.js (I have omitted unrelated files) There is a server.js outside ...