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?