Pyae Phyoe Shein
Pyae Phyoe Shein

Reputation: 13787

AWS Lambda nodejs mysql query inside loop is not working

module.exports.handler = async (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  let index = 0;
    var client = mysql.createConnection({
      host: process.env.rds_host,
      user: process.env.rds_username,
      password: process.env.rds_password,
      port: process.env.rds_port
    });
    client.connect((err) => {
      if (err) throw err;
      console.log("Connected!");
    });
  let array = [];
  let queries = ["query1", "query2", "query3", "query4"];
  queries.map(q => {
    array.push(getQueryResult(client, q));
  });
  Promise.all(array).then(result => {
    console.log(result);
  });
  callback(null, {});
};

const getQueryResult = async (client, query) => {
  return new Promise((resolve, reject) => {
    client.query(query, function (err, result) {
      if (err) {
        reject(err);
      }
      resolve(result);
    });
  });
};

Above is my lambda scripts to execute multiple query from mysql. The problem is I didn't get any result and error message from above scripts. Please help me something is missing inside my scripts?

Upvotes: 0

Views: 372

Answers (2)

IftekharDani
IftekharDani

Reputation: 3729

The issue is >> code is not waiting to finish Promise

You can resolve by :

Add callback in then

Promise.all(array).then(result => {
    console.log(result);
    callback(null, {});
  });

OR

Use await

let result = await Promise.all(promiseArray);
console.log(result)
callback(null, {});

Note: Use try-catch to handle error in for await

Also, don't use map to loop array instead use For loop.

Upvotes: 2

rags2riches-prog
rags2riches-prog

Reputation: 1761

There are two or three (potential) issues with your code above:

  1. Your if statement does not get evaluated because of the typeof client predicate does not return true.

  2. your mysql port conflicts with your localhost port (assumption)

Change your if block as such:

 // check if `dotenv` has been called if you use it
 require('dotenv').config();
 
 // access the state property on mysql object
 // if you have closed your connection previously
 // this will get evaluated by the parser
 if (mysql.state === "disconnected") {  
 
      var client = mysql.createConnection({
          host: process.env.rds_host,
          user: process.env.rds_username,
          password: process.env.rds_password,
          port: process.env.rds_port        // is your port the same as your localhost?
          // include your database name here
        });
     
      // I suggest you to await your client connection
      // since mysql executes sequentially, not asynchronously
      client.connect(function(err) => {
          if (err) {
            console.error('error connecting: ' + err.stack);
            return;
          }
          console.log("Connected!");
        });
 }

if the error persists, it means that your enviroment variables are not set correctly so your db configuration should be reviewed (see inline comments).

Upvotes: 1

Related Questions