2

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

1 Answer 1

1

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]});)
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the help can you please tell me where should I use promise.all in my code.
In getChartData function. remove the responses variables and the return statement for the code i've posted.
the running time is still 56 seconds

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.