When using lambda functions with async.parallel, the last callback function may not be executed

I have created a lambda function in node.js with two files - index.js and loader.js. The problem I am facing is that the callback function in index.js is not being executed after the method in loader.js completes its execution.

Below is the code:

var yates = require("./yatesLoader");

module.exports.handler = function(event, context) {
    if(event.app === undefined || event.data === undefined){
        context.fail("invalid request");
    }
    if(event.app === 'YatesDataLoader'){
        var result = yates.sendNotification(event.data, function(err, resp){
            if(err){
                console.log("Error : " + JSON.stringify(err));
                context.done(null, "error occurred");
            }
            console.log("response : " + JSON.stringify(resp));
            context.done(null, resp);  // SUCCESS with message
        });
    }    
};

Code in loader.js

var config = require("./config");
var optDynamo = config.DynamoDb;
var optSlack = config.Slack;

var async = require("async");
var req = require("request");
var AWS = require("aws-sdk");

AWS.config.update({
  region: optDynamo.region
});

var DynamoDb = new AWS.DynamoDB();

var sendNotification = function(data, callback){
    async.parallel([
        sendSlackNotification.bind(null, data, cb),
        saveDataToDynamoDb.bind(null, data, cb)     
    ], function(err, results){
        if (err) {
            console.error("Error JSON:", JSON.stringify(err, null, 2));
            return callback(err, null);
        } else {
            console.log("Success:", JSON.stringify(results, null, 2));
            return callback(null, results);
        }
    });
};

var cb = function(err, resp){
    if(err){
        console.log("Error");
    }else {
        console.log("success");
    }   
};

var saveDataToDynamoDb = function(data, cb){
    var params = {
        "TableName" : optDynamo.table,
        "Item" : {
            "TimeStamp" : {"S" : new Date().toString() },
            "ErrorMessage" : {"S" : data }
        }
    };

    console.log("Adding new data to DynamoDb");
    DynamoDb.putItem(params, function(err, data){
        if (err) {
            console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
            return cb(err, null);
        } else {
            console.log("Added item:", JSON.stringify(data, null, 2));
            return cb(null, data);
        }
    });
};

var sendSlackNotification = function(data, cb){
    var options = {
        method : 'post',
        body : {"text" : data},
        json : true,
        url :  optSlack.url
    };
    console.log("sending msg to slack");
    req(options, function(err, resp){
        if(err){            
            console.error("Unable to send message to Slack. Error JSON:", JSON.stringify(err, null, 2));
            return cb(err, null);
        } else {
            console.log("Message sent to Slack:", JSON.stringify(resp, null, 2));
            return cb(null, resp);
        }
    })
};

module.exports = {sendNotification : sendNotification};

Any help or insights on what might be causing this issue would be greatly appreciated.

Answer №1

One reason for this issue is related to how you are using the .bind() method. It is impacting the arguments passed into both saveDataToDynamoDb() and sendSlackNotification(). As a result, the actual structure they see is:

var saveDataToDynamoDb = function(data, cb, next) { ....

In this setup, next represents the callback that the async library anticipates you to invoke. You have the option to call next after executing cb.

var saveDataToDynamoDb = function(data, cb, next){
    ...
    DynamoDb.putItem(params, function(err, data){
        if (err) {
            cb(err, null);
            return next(err, null);
        } else {
            cb(err, null);
            return next(null, data);
        }
    });
};

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

Issue with the _.filter function in lodash library when used in a Node.js environment

My goal is to remove rows from a CSV file that already contain email addresses found in Mailchimp. Although I attempted to achieve this with a function, it seems that the number of elements returned is not accurate: async function testDeleteEmails(listID, ...

Can an Angular 5 web application be developed without using Node.js/npm?

I want to develop an Angular 5 web application using Java, but my boss prefers not to use Node.js/npm. Is it possible to build an app without Node.js/npm and rely solely on Java? Most of the resources I've come across recommend using Node.js/npm, inc ...

Dealing with Database Timeout in Express JS

I have been trying to extract SQL query execution into a separate file to prevent code repetition, but I am facing timeout issues during execution. var mysql = require('mysql'); const connectionData = { host: 'localhost', user: ...

How can I restrict access to localhost:3000 so that only my device can access it within the network?

Currently, I am utilizing express.js for hosting an HTTP server. Is there a method available to restrict access to port 3000 through my IP address for other devices on the network? ...

Challenges faced with password hashing in Express.js

Can anyone assist me with the process of hashing passwords? I had a functional login/register feature on my express app until I integrated bcrypt. After registering a User, I can see that the password is hashed in the Database. However, when attempting to ...

Sorry, access is not available due to CORS policy restrictions, even after 'Access-Control-Allow-Origin' has been set

My issue lies in the CORS configuration on render.com, where I am hosting both the client and server. Despite setting up cors to allow the origin that's being blocked, I keep encountering this error. The error message is: video-streaming-client.onren ...

Changing the host domain to a non-.com extension in Angular-cli while serving for development

While running an ng serve on my angular cli build, I am attempting to use a .ca domain as the host in order to address CORS and cookie issues during development. Interestingly, when using a .com domain, everything functions smoothly: Functioning with .com ...

The parameter value experiences an abrupt and immediate transformation

I recently created an electron app using Node.js and encountered a peculiar issue that I am unable to resolve: Below is the object that I passed as input: { lessons: [ name: "math", scores: [90, 96, 76], isEmpty: false ] } ...

What steps can be taken to address an overflow in the _connectionQueue of a Pool?

I am facing an issue with my Node.js code where the connection pool doesn't seem to be working as intended. The _connectionQueue of the Pool object keeps growing endlessly, causing the app to crash. Despite creating a pool and having pre-made connecti ...

"Troubleshooting: Node.js encountering a path error while loading a JSON file with

I am organizing a collection of folders and files structured like this: viz |_ app.js // node application |_ public |_ css |_ bubblemap.css |_ images |_ nuts |_ nuts0.json |_ script ...

Step-by-step guide on installing solely 'devDependencies' with npm

Looking to specifically install only the "devDependencies" from my package.json file, I've attempted various commands with no success. Each command ends up installing both production and development dependencies, which is not what I want. npm install ...

What is the method for Java-based services to communicate with a ZeroMQ broker written in C?

I have created a request-reply broker using zeromq and C programming. The broker is responsible for directing client requests to the appropriate services and then sending the reply back to the client. These services are developed in JAVA. Could someone pr ...

Facing a problem with running npm start on jHipster

I am currently working on a jhipster project on my MacBook Pro running macOS Mojave v.10.14.4. After successfully compiling with npm start, the code continues to compile multiple times without any changes. Eventually, it throws the following error: DONE ...

Redirecting the socket.io client to the Heroku service

Recently, I developed a real-time chat application using socket.io, Node.JS, and express. It was functional on my local server but now I want to connect it to an existing Heroku service instead. How can I achieve this? Once I tried the following code, va ...

The Node.js Express application that utilizes the fast-csv stream parser is unable to redirect when encountering "data-invalid" errors

A new tool is in the works to streamline the process of uploading CSV files into a database and presenting the data in various formats. The current issue at hand involves an error message that pops up when attempting to upload a faulty file with 6 columns ...

The putObject function in Node.js extends the size of an object on the server

Currently, I am working on pushing an image to an S3 instance using Nodejs with the aws-sdk. The approach involves reading from a file on the client and saving it on the server within a meteor framework. However, my goal is to directly upload it to the S3 ...

Accessing secure managed Redis using Node.js authentication credentials

Upon further reflection, the question that arises is how to connect to digitalocean's managed redis with node-redis using tls. Although I can establish a connection with the redisinsight GUI client using a username and password without any issues, I ...

Activity Timeout in Azure Durable Functions

Within my activity function, I have the following code block: do { await timeout(500); } while (await getStatus() === false); Here's what each part of the code does: function timeout(ms) { return new Promise(resolve => setTimeout(reso ...

`Grunt.js watch for Browserify`

Hi there! I'm just starting to explore Grunt.js. Up until now, my process involved running: browserify ./js/app.js -o ./js/app.bundle.js each time a file was changed and saved. Now, I am aiming to streamline this by using Grunt (version 0.4.2) wat ...

Using TypeORM to establish a ManyToOne relationship with UUID data type for the keys, rather than using integers

I am currently facing a challenge in my Typescript Nestjs project using TypeORM with a PostgreSQL database. The issue arises when trying to define many-to-one relationships, as TypeORM insists on creating an ID field of type integer, while I prefer using U ...