Question:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const params = { TableName: 'item-table', FilterExpression : "#tagname = :itemId", ExpressionAttributeNames: {"#tagname": "itemId"}, ExpressionAttributeValues: {":itemId": "000001"} }; var item =""; dynamo.scan(params, function(err, data) { if (err) { console.error("Unable to query. Error:", JSON.stringify(err, null, 2)); item = err; } else { console.log("Query succeeded."); data.Items.forEach(function(item) { item += item.itemName; }); } return item; }); |
Scan is not waiting to return the output but going to next step. How can we run synchronous call from lambda to dynamodb.
Answer:
If you really need synchronous scan, you can use one of the ways below:
1. Using Promise resource of JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
const params = { TableName: 'item-table', FilterExpression : "#tagname = :itemId", ExpressionAttributeNames: {"#tagname": "itemId"}, ExpressionAttributeValues: {":itemId": "000001"} }; function scan(params) { return new Promise((resolve, reject) => { dynamo.scan(params, (err, data) => { if (err) reject(err); else resolve(data); }; }; } async function syncScan() { var data; try { data = await scan(params); console.log("Query succeeded."); } catch (err) { console.error("Unable to query. Error:", JSON.stringify(err, null, 2)); } return data; } syncScan(); |
2. Using the aws-sdk return objects:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const AWS = require('aws-sdk'); AWS.config.update({ region: 'sa-east-1' }); const docClient = new AWS.DynamoDB.DocumentClient(); async function syncScan() { const params = { TableName: 'item-table', FilterExpression : "#tagname = :itemId", ExpressionAttributeNames: {"#tagname": "itemId"}, ExpressionAttributeValues: {":itemId": "000001"} }; const awsRequest = await docClient.scan(params); const result = await awsRequest.promise(); console.log(result.Items); // <<--- Your results are here } syncScan(); |