I have been stuck with this for a couple of hours now, cannot understand why this simple async function is returning an empty array? I am trying to query a number of items from my DynamoDB table using a Lambda function but I cannot get the function to pause using async/await and I cannot understand why. I have logged following the push and the array is being filled up with lovely objects, but it just doesn't wait for it to finish before calling done. Please. Help. Going crazy.
'use strict';
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = async(event, context, callback) => {
const done = (err, res) => {
const response = {
statusCode: err ? '400' : '200',
body: err ? JSON.stringify(err) : JSON.stringify(res),
headers: {
'Access-Control-Allow-Origin': '*'
}
};
callback(null, response);
};
const { body } = event;
// If in prod env, parse
if (typeof body === 'string') {
body = JSON.parse(body);
}
const groupIds = body.groupIds;
let events = [];
await groupIds.forEach(groupId => docClient.query({
TableName: 'events',
IndexName: 'groupId-creationDate-index',
KeyConditionExpression: 'groupId = :g',
ExpressionAttributeValues: { ':g': groupId }
}, (err, data) => {
if (err) {
done(err);
}
else {
events.push(...data.Items);
}
}));
done(null, events);
};