I am performing input operation on db and trying to return response.
var response = {}
try {
db.put({},(err, data) => {
if(err) {
response["message"] = err.message
response["code"] = 400
} else {
response["message"] = "Group created"
response["code"] = 201
response["body"] = data.Item
}
})
} catch (error) {
response['message'] = "Something went wrong"
response['code'] = 500
} finally {
return response
}
This code returns null object on success whereas when I tried setting timeout after the db call it returned full response. I think finally block runs without awaiting db call response.
Yes, that would make sense if db.put
is asynchronous.
For DynamoDB it looks like you can return a Promise. You could then use await to wait for the response in order to return it.
It would become something like this:
const func = async() => {
const response = {}
try {
try {
const rv = await db.put({}).promise();
response["message"] = "Group created"
response["code"] = 201;
response["body"] = rv.data.Item;
} catch (err) {
response["message"] = err.message;
response["code"] = 400;
}
} catch (error) {
response['message'] = "Something went wrong";
response['code'] = 500;
} finally {
return response;
}
}
func().then((val) => console.log(val));