Reputation: 2754
I have an async function that uses pg to execute a query for a function. It's not returning anything, I'm not sure if it's the way I call my async function that's the issue. The response_test always returns as an empty json object
const pg = require('pg');
const Query = require('pg').Query;
const pool = new pg.Pool();
const response = {...my format for response..}
module.exports.login = (event, context, callback)=> {
try{
var client = new pg.Client(conn);
client.connect();
var query = "select a_function_that_returns_1_row($1, $2)";
var params = ['param1', 'param2'];
var reponse_test = get_token(query, params);
client.end();
response.body = JSON.stringify(
{
reponse_test
}
)
callback(null, response);
} catch(err){
serverError.body = JSON.stringify({
error: err
});
callback(null, serverError);
}
}
async function get_token(query, params){
try {
const res = await pool.query(query, params);
return res.rows[0];
} catch (err) {
console.log(err.stack)
}
}
Upvotes: 1
Views: 1036
Reputation: 7770
The problem is your get_token
method is async but you are not awaiting it while calling. You also don't need callback. Just make your lambda function async and return the response. Something like this
const pg = require("pg");
const Query = require("pg").Query;
const pool = new pg.Pool();
const response = {};
module.exports.login = async event => {
try {
const client = new pg.Client(conn);
client.connect();
const query = "select a_function_that_returns_1_row($1, $2)";
const params = ["param1", "param2"];
const reponse_test = await get_token(query, params);
client.end();
response.body = JSON.stringify(
{
reponse_test
}
);
return response;
} catch (err) {
serverError.body = JSON.stringify({
"error": err
});
return serverError;
}
};
async function get_token(query, params) {
try {
const res = await pool.query(query, params);
return res.rows[0];
} catch (err) {
console.log(err.stack);
}
}
Upvotes: 2