为什么我得到每条记录两次都得到回应

时间:2019-07-14 10:09:01

标签: javascript node.js aws-lambda amazon-dynamodb serverless-framework

为什么我两次都获得所有记录? 当我使用AWS CLI检查对应的dynamoDB表时,仅存在两条记录。

从aws文档网站复制了“ onScan”功能的代码。 https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.04.html

var AWS = require("aws-sdk");
var commons = require("../../Utils/common_utils");
AWS.config.setPromisesDependency(require("bluebird"));
var docClient = new AWS.DynamoDB.DocumentClient();

module.exports.listProduct = (event, context, callback) => {
  var items = [];
  var params = {
    TableName: process.env.PRODUCT_TABLE
  };
  docClient
    .scan(params, onScan)
    .promise()
    .then(res => {
      callback(null, {
        headers: commons.getCorsHeader(),
        statusCode: 200,
        body: JSON.stringify({
          message: "Success",
          products: items
        })
      });
    });

  function onScan(err, data) {
    if (err) {
      console.error(
        "Unable to scan the table. Error JSON:",
        JSON.stringify(err, null, 2)
      );
    } else {
      items = items.concat(data.Items);
      if (typeof data.LastEvaluatedKey != "undefined") {
        console.log("Scanning for more...");
        params.ExclusiveStartKey = data.LastEvaluatedKey;
        docClient.scan(params, onScan);
      }
    }
  }
};

这是我的输出:

{
        "message": "Success",
        "products": [
            {
                "price": "1",
                "product_name": "Iteraconazole Tab",
                "product_id": "Iteraconazole Tab1"
            },
            {
                "price": "200",
                "product_name": "Luliconazole",
                "product_id": "Luliconazole200"
            },
            {
                "price": "1",
                "product_name": "Iteraconazole Tab",
                "product_id": "Iteraconazole Tab1"
            },
            {
                "price": "200",
                "product_name": "Luliconazole",
                "product_id": "Luliconazole200"
            }
        ]
    }

产品中的记录只有两条。预期的输出应该是两个记录,但得到4。

0 个答案:

没有答案