0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for sharing! Unfortunately, data seems to be undefined always. VS Code is highlighting await and says "'await' has no effect on the type of this expression".
Nevermind, Hlib it works great, you just have to .promise() the docClient.query()! Is this the right syntax or am I not supposed to do that? Thank you so much for your help. I'll look into resolve/reject.
@DanielSegura Sure, you're absolutely right! .promise() turns your query into promise so that you can easily use then/catch or any other valid syntax to make promise execute and be handled. docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/…
Hey I can't thank you enough. Seriously, I've literally spent like 4 hours trying to get this working, I even went through the doc link you sent above and wouldn't click on my brain. I just refactored it into a promise and did something like .then( (data,err) => { ... } and seems to be working just fine!
@DanielSegura Congrats! Happy coding! ;)

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.