node.js - 如何使用 Amazon DynamoDB JavaScript SDK 与 Promise

标签 node.js express promise amazon-dynamodb

我正在使用 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/

相关文章:

javascript - 刷新后使用 ng-click 在 html 中显示 session

Javascript - 在 Websocket 上使用 promise ?

javascript - 如何用js将数据写入xls表

javascript - Node.js、Express.js 不向客户端发送文件

javascript - express.js 异步路由器和错误处理

express.js 中的 JSON 序列化算法

node.js - 请求和响应对象何时填充到 Express 应用程序中

node.js - 在循环内创建模型上的 Sequelize 嵌套 promise

javascript - 如何在 promise 数组中引用对象值?

javascript - 如何获取客户姓名并将其放入字符串中?