0

I'm trying to do something that should be very straightforward. I need to wait for mysql query results so that they can be returned as an HTTP response. However, the only examples I can find simply write query results to the console and do not wait for results.

I've tried many approaches given online for generic wait/promise. Here's the latest one I tried using util.promisify() from this post; node.js async/await using with MySQL

Here is my sample code;

function callbackQuery(error: any, results: any, field: any) {
    if (error) {
      console.log(error);

      return {
        statusCode: 500,
        body: JSON.stringify({ message: 'There was an error' }),
      };
    } else {
      console.log(results);

      return {
        statusCode: 200,
        body: JSON.stringify({ message: 'There was NO error' }),
      };
    }
  }

  function queryWrapper() {
    connection.query('SELECT * FROM my_table', callbackQuery);
  }

  const myQuery = util.promisify(queryWrapper).bind(connection);

  (async () => {
    try {
      const res = await myQuery();
      console.log(res);

      return res;
    } finally {
      connection.end();
    }
  })();

And here are the results;

Request from ::ffff:127.0.0.1: GET /.netlify/functions/ ◈ lambda response was undefined. check your function code again Response with status 500 in 100 ms.[ RowDataPacket { } ]

So, essentially, no waiting is happening because the 'lambda response was undefined' is output before the query result set. I would expect the response, 'There was NO error' instead. Does anyone have a simple example of how to wait for the data?

JediPotPie
  • 1,068
  • 3
  • 14
  • 21
  • https://stackoverflow.com/questions/44004418/node-js-async-await-using-with-mysql – hoangdv Mar 03 '22 at 01:19
  • @hoangdv Not sure what this comment means because I included this link in my question. Are you saying I implemented the proposed solution incorrectly? – JediPotPie Mar 03 '22 at 02:14
  • I'm sorry, i mean just follow the answer in the question, try to make it work at first. – hoangdv Mar 03 '22 at 02:59
  • queryWrapper isn't returning anything. I wrote a doc specifically when seeing so many people struggle with mysql in node. Hope it helps: https://evertpot.com/executing-a-mysql-query-in-nodejs/ – Evert Mar 03 '22 at 05:31

0 Answers0