legit98
legit98

Reputation: 57

Using async and await to handle queries

Having issues with using async and await. I'm executing two queries and then saving the result to a temp variable. After I have collected the response from all executed queries, I'm going to send that to the client.

Here is my current example code.

module.exports = (app) => {

  app.get('/api/stats', (req, res) => {
    let fetch1 = '';
    let fetch2 = '';

    conn.query('query here', [], async (error, results) => {
      if (error) {
        return res.send({
          success: false,
          message: 'There was an error.'
        });
      } else {
         fetch1 = results;
      }
    });

    conn.query('query here', [], async (error, results) => {
      if (error) {
        return res.send({
          success: false,
          message: 'There was an error.'
        });
      } else {
        fetch2 = results;
      }
    });


    // I need to wait until the queries have resolved so that I can send the correct data
    return res.send({
      success: true,
      fetch1: fetch1,
      fetch2: fetch2
    });
  });
};

I basically need to wait until the queries have been resolved so that I can send the correct data towards the end.

Can anyone explain how I can use await and async to accomplish this?

Thanks.

Upvotes: 0

Views: 265

Answers (2)

yeerk
yeerk

Reputation: 2667

You can only await a Promise, so for functions that don't return Promises you need to create a Promise wrapper. This needs to be done per call that would previously use a callback, but you can make a helper function per function you need to wrap.

function queryPromise(query, parameters) {
    return new Promise((resolve, reject) => {
        conn.query(query, parameters, (err, results) => {
            if(err) {
                reject(err);
            } else {
                resolve(results);
            }
        });
    });
}

module.exports = (app) => {
    app.get('/api/stats', async (req, res) => {
        try {
            let fetch1 = await queryPromise('query here', []);
            let fetch2 = await queryPromise('query here', []);

            res.send({
                success: true,
                fetch1: fetch1,
                fetch2: fetch2
            });
        } catch {
            res.send({
                success: false,
                message: 'There was an error.'
            });
        }
    });
};

Upvotes: 3

Shean
Shean

Reputation: 58

From my knowledge, I usually apply async to functions and perform await on certain variables (inside the function) that need to be acquired from a specific database. So to implement this into your function containing the async tag, you could possibly do:

fetch1 = await results; fetch2 = await results;

This will wait until the data is attached onto the variable fetch1 and fetch2 before continuing on with the code.

Sorry if this was very vague, hopefully this was somewhat helpful.

Upvotes: 0

Related Questions