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
..
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
.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM