0

I am working on API development using AWS API getaway and lambda. I am using Serverless MySQL https://www.npmjs.com/package/serverless-mysql package for mysql connection and operation. but I am unable to execute multiple queries. Please check below code.

It's showing error "Parsing error: Unexpected token connection".

var sql_1 = 'Query 1';
let rows = await connection.query(sql_1);

rows.forEach(function (row) {

    var sql_2 = 'Query 2';
    let rows = await connection.query(sql_2); // I am refering id in sql2 from result of sql_1
});
1
  • It's showing error "Parsing error: Unexpected token connection". or we can say syntax error I want to write the multiple queries in a single lambda function Commented Jul 24, 2019 at 12:58

2 Answers 2

1

I am confused by your code, as you are reassigning a variable you are iterating on aside from multiple syntax errors.

But I think your issue is that you are misunderstanding how to use asynchronous JavaScript properly. ForEach does not wait for your query to finish before continuing.

Better would be to use something like Promise.all() to wait for all of your queries to return asynchronously.

let q1Rows = await query(...);

let otherQueries = Promise.all(q1Rows.map(async (row) => await query(row.someData)));
// otherQueries is now an array of all the returned queries in order
Sign up to request clarification or add additional context in comments.

Comments

0

You can write the multiple queries using Promise await.

var sql_1 = 'Query 1';
let rows = await connection.query(sql_1);

let resultTemp=[];
    await Promise.all(rows.map(async (row) => {
       var sql_2 = 'Query 2';
       let result = await connection.query(sql_2 );
            resultTemp.push(result);

     }));

 context.succeed(resultTemp);

1 Comment

Promise.all returns an array of return values, why would you push to an array? This is a copy of my answer with significantly worse style practices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.