This question already has an answer here:
I'm trying to write an Amazon Lambda function in Node.js to return elements in a DynamoDB database. I cannot use batchGetItem() because I am querying a secondary index, so I must use query. There are several keys that I want to query over, so I tried to use a for loop to issue multiple query requests and keep concatenating the responses, finally returning the end result. I need a way for the function to wait until all the responses are received before issuing the final callback. Any ideas of how to implement this?
toReturn = [];
for (var i in zipCodes){
var params = {
TableName: 'hosts',
IndexName: 'zip-index',
KeyConditionExpression: 'zip = :hkey',
ExpressionAttributeValues: {
':hkey': zipCodes[i]
}
};
dynamo.query(params, function(err, data) {
if (err){
console.log(err);
callback(null, errResponse);
}
else {
toReturn = toReturn.concat(data.Items);
if (i == zipCodes.length-1){
//trigger some event to send the response
}
}
//wait for all the items to get added to toReturn
var response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*" // Required for CORS support to work
},
body: JSON.stringify({
message: 'Stores retrieved succesfully!',
items: toReturn,
input: event,
})
}
callback(null, response);
via Jay Vaidya
No comments:
Post a Comment