Ad

How To Put AWS DynamoDB DocClient.get Item Into Variable?

I'm currently working with AWS SDK and DynamoDB in my code but the main problem which I constantly encounter is finding scope of variables if I create an asynchronous chain of events.

This is for my node.js server which will run a telegram bot and retrieve/store data in my AWS DynamoDB. It works with a lot of nested calls and passing on variables but makes the code very complicated.

What I want to achieve is something similar to ASYNC/AWAIT.

async DB(){
  let paramsGet = { TableName:'some_table', Key:{"id":some_id} }
  let database_item = await docClient.get(paramsGet, function(err,data){
    if(err){
      console.log(err)
    } else {
      console.log("SUCCESSFULL GET");
      return data //RETURN IT TO VARIABLE
    }
  }

  let paramsPut = {
          TableName: "my_table", 
          Item: {
                  //THESE VALUES SHOULD WAIT FOR GET TO FINISH
                  //THEN SEND IT TO DB
                  "id":database_item.id,
                  "name":database_item.name,
                  "value":database_item.value
                }
  }

  docClient.put(paramsPut, function(err,data){
    if(err){
      console.log(err)
    } else {
      console.log("SUCCESSFULL PUT");
    }
  }

}
DB();

When I do this let db_item = await docClient.get(...) and console.log(db_item) it will show a stream of data which doesn't look like anything being returned like data in if(err){ console.log(err) } else { console.log(data)}?

How should I handle this return value? Is it a promise or something else that needs to be parsed? I cannot seem to find the db_item.type..

Ad

Answer

Almost all AWS JavaScript SDK methods have .promise() function returning a Promise of the called operation.

As await works with Promises, you can use that for your needs:

try {
   let res = await docClient.get(paramsGet).promise();
   let database_item = res.Item;
   console.log("SUCCESSFULL GET", database_item);
} catch(err) {
   console.log(err);
}

You can find the description of the structure of the returned object in the documentation.

Similar for .put.

Ad
source: stackoverflow.com
Ad