简体   繁体   中英

AWS Dynamodb not fetching data synchronously by node js

I am new on node js dynamo db I wrote a node js sdk to fetch one row from a table ona dynamodb. It is fetching data correctly but not immediately for this I got error

My code is below a simple code

var AWS = require("aws-sdk");

var config = function(){

AWS.config.update({region: 'us-east-1'});

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

var params = {
  TableName: 'tblConfigs',
  // Key: {
  //   "id" : {S: "1"},
  // }
  ExpressionAttributeValues: {
   ":v1": {
     S: "1"
    }
  },
  FilterExpression: "id = :v1",
};
var v;
var json = ddb.scan(params, function(err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    v = data;
    // console.log(JSON.stringify(data.Item));
   // return JSON.stringify(data.Item);
  }
});
// if(v=="u")
// for(var i=0;)

v = v.Items[0];

// for()

var con = {
    "host": v.endpoint.S,
    "user": v.endpoint.username.S,
    "password": v.endpoint.password.S,
    "database": v.endpoint.database_name.S
};

return con;
}

And I got the below error

> config()
TypeError: Cannot read property 'Items' of undefined
    at config (repl:31:7)

as v is undefined so it is giving the error but v is not undefined when I execute the code in node console it first time gave undefined next time it gave value

like below

> v
{ Items:
   [ { password: [Object],
       stage: [Object],
       username: [Object],
       id: [Object],
       endpoint: [Object],
       database_name: [Object] } ],
  Count: 1,
  ScannedCount: 1 }

how can I fetch the row immediately not after some time? IS there any good way in dynamodb I tried, get, getItem, scan, query all are giving data correctly but not immediately...Please suggest

You are missing one important thing: Javascript execution is asynchronous. As long as you are not using async/await syntax you have to "play" with callbacks like this:

var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });

function loadConfig(callback) {
    var params = {
        TableName: 'tblConfigs',
        ExpressionAttributeValues: {
            ':v1': {
                S: '1'
            }
        },
        FilterExpression: 'id = :v1'
    };

    ddb.scan(params, function (error, data) {
        if (error) {
            callback(error);
        } else {
            var item = data.Items[0];
            callback(null, {
                'host': item.endpoint.S,
                'user': item.endpoint.username.S,
                'password': item.endpoint.password.S,
                'database': item.endpoint.database_name.S
            });
        }
    });
}

loadConfig(function (error, configuration) {
    if (error) {
        console.log(error);
    } else {
        // Your connection logic (JUST AN EXAMPLE!)
        var connection = mysql.connect({
            host: configuration.host,
            user: configuration.user,
            password: configuration.password,
            database: configuration.database
        })
    }
});

Btw. storing database configurations in DynamoDB isn't a good solution, i would recommend to check AWS Systems Manager Parameter Store .


Edit

To give you a short example how the async/await syntax looks like

var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });

const loadConfig = async () => {
    const { Items } = await ddb.scan({
        TableName: 'tblConfigs',
        ExpressionAttributeValues: {
            ':v1': {
                S: '1'
            }
        },
        FilterExpression: 'id = :v1'
    }).promise();

    const item = Items[0];
    return {
        'host': item.endpoint.S,
        'user': item.endpoint.username.S,
        'password': item.endpoint.password.S,
        'database': item.endpoint.database_name.S
    };
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM