I have a function that gets some data from DynamoDB using docClient.query(). I'm able to retrieve data and print it on console e.g., console.log(data))
, but if I try to return data
I always get undefined.
I thought that function (err,data){ ... }
was a callback of the query()
function and was hoping it would wait for the value to be available to before returning.
Clearly I'm new with AWS SDK and async functions, couldn't find documentation that used return
in the way I needed.
I just need the aliasHasRole
to return the isAuthorized
JSON so I can use it elsewhere outside the function.
function aliasHasRole(an_alias, a_role) {
const params = {
TableName: 'xxxxxxx',
KeyConditionExpression: '#alias= :alias AND #Role= :Role',
ExpressionAttributeNames: {
'#alias': 'alias',
'#Role': 'Role'
},
ExpressionAttributeValues: {
':alias': an_alias,
':Role': a_role,
},
};
docClient.query(params, function (err, data) {
if (err) {
console.log("Error when attempting table query, see below:\n\n" +
JSON.stringify(err, null, 2));
return err;
} else {
var isAuthorized = data.Count === 1 && data.Items[0].alias === an_alias && data.Items[0].Role === a_role ? true : false;
console.log(1,'Access', isAuthorized ? 'Granted' : 'Denied', 'for alias "' + an_alias + '".\n');
return isAuthorized; //always returns undefined
}
})
}
console.log(aliasHasRole("fooAlias","barRole")) // returns undefined.
Surely that's the issue related to asynchronous code. If you are able to use docClient.query
with async/await syntax, then you can wait for its execution and return value according to its result. You can also use Promise syntax if it's necessary to know the err
value (if exists). Then you can also use resolve/reject in your function.
Solution with async/await syntax:
async function aliasHasRole(an_alias, a_role) {
const params = {
TableName: 'xxxxxxx',
KeyConditionExpression: '#alias= :alias AND #Role= :Role',
ExpressionAttributeNames: {
'#alias': 'alias',
'#Role': 'Role'
},
ExpressionAttributeValues: {
':alias': an_alias,
':Role': a_role,
}
};
const data = await docClient.query(params);
if (!data) return false;
const isAuthorized = data.Count === 1 && data.Items[0].alias === an_alias && data.Items[0].Role === a_role ? true : false;
return isAuthorized;
};
aliasHasRole("fooAlias", "barRole").then(console.log).catch(console.log);
UPDATE
What really helps is making your query a promise with .promise()
. Then it can be easily executed and handled with then/catch syntax.