varun chauhan
varun chauhan

Reputation: 89

Mysql and node: Running query in parallel

I have a rest api that takes 3 query and return the data in json format to front end of angular. However the query takes almost 1 min to run and send the json format. Can anyone help me to optimize the code so that I can get a better running time.

Here is the code:

async function getChartData (req, res){
    try{

        var sqlquery=" " 
        var sqlsecond=" "
        var sqlthird=" "

        let result1 = await selectquery(sqlquery)

        let result2 = await selectquery(sqlsecond)

        let result3 = await selectquery(sqlthird)

        return res.json({result1:result1, result2:result2, result3:result3});

    }
    catch(err){
        // response.status(500).end();
        console.log(err);
    }
  }


async function selectquery(sqlquery){
    return new Promise((resolve, reject) => {
        mysqlConnection.query(sqlquery,(err,result)=>{
            if(err){
                reject(err);
            }
            else{
                resolve(result);
            }
        });
    });
}

Upvotes: 2

Views: 422

Answers (1)

michaelitoh
michaelitoh

Reputation: 2340

If the queries does not depends each other is not neccesary you await the response.

Use Promise.all and the queries are going to run in parallel.

   Promise.all([selectquery(sqlquery),selectquery(sqlsecond),selectquery(sqlthird)])
          .then(res=> res.json({result1:res[0], result2:res[1], result3:res[2]});)

Upvotes: 1

Related Questions