Matteo
Matteo

Reputation: 13

AWS DynamoDB parsing returned data

I am trying to use JS to query DynamoDB and parse the returned data. I must admit that I am new to JavaScript but I am having some weird behaviours.

In the following function I am passing an array of dates and I am retrieving objects from my table

var queryDynamo = function(dateArray){
  console.log(dateArray)
  for (var i = 0; i < dateArray.length; i++) {
    var params = {
        TableName : "myTable",
        KeyConditionExpression: "#day = :st ",
        ExpressionAttributeNames:{
            "#day": "day"
        },
        ExpressionAttributeValues: {
            ':st': dateArray[i]
        }
    };
    var resp = docClient.query(params, function(err, data) {
        if (err) {
                console.log("ERR:"+JSON.stringify(err, undefined, 2))
            } else {
                data.Items.forEach(function(element) {
                    console.log(element)
                });        
            }
        });
      }
      console.log(resp.response)
      return;
    }

--> The following is the output

constructor {request: constructor, data: null, error: null, retryCount: 0, redirectCount: 0, …}
        data:
          Count: 4
          Items: (4) [{…}, {…}, {…}, {…}]
          ScannedCount: 4
          __proto__: Object
          error: null
        httpResponse: constructor {statusCode: 200, headers: {…}, body: Uint8Array(1134), streaming: false, stream: i, …}
        maxRedirects: 10
        maxRetries: 10
        nextPage: ƒ (e)
        redirectCount: 0
        request: constructor {domain: undefined, service: t.c…r.t.constructor, operation: "query", params: {…}, httpRequest: constructor, …}
        retryCount: 0
        __proto__: Object

The query succeeds but the result is kind of weird.

Upvotes: 1

Views: 1508

Answers (1)

jarmod
jarmod

Reputation: 78603

You are attempting to print the response data before it exists. Your console.log(resp.response) line is executing before the DynamoDB query has completed and its results have been unmarshalled. This is a common gotcha in asynchronous JavaScript.

One way to see the response data in the AWS.Request object is to wait for it, like this (though you would never typically do this in JavaScript):

var req = docClient.query(params, function(err, data) {
  // as before: handle err, data
)};

setTimeout(function () {
  console.log('Response data:', JSON.stringify(req.response.data));
}, 2000);

A more common pattern is to use the promise variants of the SDK methods, like this:

docClient.query(params).promise()
  .then(data => doSomething(data))
  .catch(err => logError(err));

Upvotes: 1

Related Questions