我正在使用 Amazon DynamoDB 和 Express。
我需要根据 Amazon DynamoDB 表中的数据呈现 View 。
当我使用回调 API 而不是尝试使用 Promise 时,我的代码工作正常。
但我想使用 Promise,因为要保持代码干净,否则我需要从 docClient.scan(params)
的回调内部调用 res.send()
。
我使用 Promise 的代码如下,我不知道出了什么问题;
async function test(params){
AWS.config.loadFromPath('./awsconfigtest.json');
let docClient = new AWS.DynamoDB.DocumentClient();
await docClient.scan(params).promise();
}
下面是路由文件的内容;
/* GET home page. */
router.get('/', function(req, res, next) {
let scanResults ;
let params = {
TableName: 'dummy'
};
test(params).then((data,err)=>{
console.log(data,err);
data.Items.forEach(function (element, index, array) {
scanResults.push({name: element.name, nodeId: element.nodeId});
console.log(element.name + " (" + typeof element.nodeId + ")");
});
});
console.log(scanResults);
res.render("index",{nodes:scanResults});
});
最佳答案
主要原因是您的 test
函数没有返回任何内容 - 您忘记了 return
关键字。
但是,我认为最佳实践是不要将 async/await
语法与 Promise 解决语法(.then .catch
)混合使用。
这是使用async/await
的方式:
async function test(params){
AWS.config.loadFromPath('./awsconfigtest.json');
let docClient = new AWS.DynamoDB.DocumentClient();
return await docClient.scan(params).promise(); // !!! You forgot return keyword
}
/* GET home page. */
router.get('/', async function (req, res, next) { // async function
try {
let scanResults;
let params = {
TableName: 'dummy'
};
const data = await test(params); // await for `data`
console.log(data);
data.Items.forEach(function (element, index, array) {
scanResults.push({ name: element.name, nodeId: element.nodeId });
console.log(element.name + " (" + typeof element.nodeId + ")");
});
console.log(scanResults);
res.render("index", { nodes: scanResults });
} catch (err) {
res.status(500).send(err); // handle exception
}
});
关于node.js - 如何使用 Amazon DynamoDB JavaScript SDK 与 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58544501/