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?

4
  • stackoverflow.com/questions/44004418/… Commented Mar 3, 2022 at 1: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? Commented Mar 3, 2022 at 2:14
  • I'm sorry, i mean just follow the answer in the question, try to make it work at first. Commented Mar 3, 2022 at 2:59
  • queryWrapper isn't returning anything. I wrote a doc specifically when seeing so many people struggle with mysql in node. Hope it helps: evertpot.com/executing-a-mysql-query-in-nodejs Commented Mar 3, 2022 at 5:31

0

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.