[英]Return values from AWS DynamoDB JavaScript SDK are undefined
I am currently using the JavaScript AWS SDK for DynamoDB and I am trying to parse the data I get from a DynamoDB call, but it always returns undefined.我目前正在使用 JavaScript AWS SDK for DynamoDB,我正在尝试解析从 DynamoDB 调用中获得的数据,但它始终返回 undefined。 It does print the result successfully, but trying to store that data in a variable is unsuccessful.它确实成功打印了结果,但尝试将该数据存储在变量中是不成功的。 Below is how I am attempting to do it.以下是我尝试这样做的方式。
const AWS = require("aws-sdk");
AWS.config.update({ region: "us-east-1" });
const dynamoDb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });
const promisify = foo =>
new Promise((resolve, reject) => {
foo((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
const params2 = {
TableName: "Users",
Key: {
userID: { S: "123456789" },
},
};
const test = params => {
dynamoDb.getItem(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data.Item);
return data.Item;
}
});
};
let user = test(params2);
console.log("User:", user);
I believe it has to do with getItem being asynchronous and I have researched how to implement a promise into this code, but I cannot get the correct syntax.我相信这与 getItem 异步有关,我已经研究了如何在此代码中实现承诺,但我无法获得正确的语法。 Any and all help is greatly appreciated.非常感谢任何和所有帮助。 Thank you.谢谢你。
The problem you have is that you are not returning anything from your test
function.您遇到的问题是您没有从test
函数返回任何内容。 So it is expected that you get undefined outside.所以预计你会在外面得到 undefined 。
Try to do it like this:尝试这样做:
// used aws promise api https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/using-promises.html
function test(params) {
return dynamoDb.getItem(params).promise();
}
test(params2).then(
user => {
console.log('User:', user);
},
error => {
console.log('Error:', error);
},
);
Some further read:一些进一步阅读:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.