I'm trying to insert bulk data into the DynamoDB table but not even a single data is getting inserted in the table using the Lambda function written in TypeScript.
Here is my code:-
import { DynamoDB } from 'aws-sdk';
import { generateUsers } from './src/generator';
const dynamodb = new DynamoDB.DocumentClient({ apiVersion: '2012-08-10' });
let response: { statusCode: number; body: string; };
/**
*
* Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format
* @param {Object} event - API Gateway Lambda Proxy Input Formatasvzsdsdsffd
*
çn * @returns {Object} object - API Gateway Lambda Proxy Output Format
*
*/
export const lambdaHandler = async (event, context) => {
try {
const users = await generateUsers(20).then(data => data.users);
users.forEach(async (user: { id: any; employeeId: any; }) => {
console.log('emp id ->', user.employeeId);
await writeData(user);
console.log('done for emp id ->', user.employeeId);
});
console.log('done for all employess');
response = {
'statusCode': 200,
'body': JSON.stringify({
message: 'mock data..',
})
}
} catch (err) {
console.log(err);
return err;
}
return response
};
const writeData = async (user: { id: any; employeeId: any; }) => {
var params = {
TableName: "MockedDataTable",
Item: {
"id": user.id,
"employeeId": user.employeeId
}
};
await dynamodb.put(params)
.promise()
.then((data) => {
console.log(data);
})
.catch(err => {
console.log(err);
});
}
I'm getting the data in the Promise and able to log very well but when it comes to writing (PutItem) call with DynamoDB table, data is not being pushed.
As per logs, data is there:-
2020-09-27T07:37:13.772Z 4463fa20-694e-14ce-a882-87cd0862eee7 INFO emp id -> 58040
2020-09-27T07:37:13.773Z 4463fa20-694e-14ce-a882-87cd0862eee7 INFO emp id -> 4968
2020-09-27T07:37:13.775Z 4463fa20-694e-14ce-a882-87cd0862eee7 INFO done for all employess
END RequestId: 4463fa20-694e-14ce-a882-87cd0862eee7
REPORT RequestId: 4463fa20-694e-14ce-a882-87cd0862eee7 Init Duration: 3362.86 ms Duration: 97.97 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 78 MB
{"statusCode":200,"body":"{\"message\":\"mock data..\"}"}
May I know where did the mistake is so that I can resolve this issue?
Im not sure if this is the answer but, You cant use async/await inside foreach. use for of instead.
for (const user of users) { console.log('emp id ->', user.employeeId); await writeData(user); console.log('done for emp id ->', user.employeeId); }
Or if you dont mind, use Promise.all if you dont mind:
await Promise.all(users.map(user => writeData(user)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.