简体   繁体   English

Lambda function 未将数据推送到 DynamoDB 表中

[英]Lambda function not pushing data into DynamoDB table

I'm running a NodeJS lambda function which is triggered by API Gateway.我正在运行由 API 网关触发的 NodeJS lambda function。

My goal is to push the data and then send a status response.我的目标是推送数据,然后发送状态响应。 I think the lambda stops running before the insertData function finishes its execution, because sometimes it works but in most requests it doesn't.我认为 lambda 在 insertData function 完成执行之前停止运行,因为有时它可以工作但在大多数请求中它不会。

Could someone lend a hand on this?有人可以帮忙吗?

Here is my code:这是我的代码:


// Set a table name that we can use later on
const tableName = "InterestRates"

// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({region: 'us-east-1'});

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
 
exports.handler = async (event) => {
    // TODO implement
    console.log(">>> Running LoanInterestRates")
    
    if(event['resource'] == '/rates'){
        if(event.httpMethod === 'POST'){
            return newRate(event);
        }
    }     
}; 

function insertData(params){
    let status;
    // Call DynamoDB to add the item to the table
    ddb.putItem(params, function(err, data) {
      if (err) {
        status = "Error";
      } else {
        status = "Success";
      } 
    });  
    return status
}

function newRate (event){ 
    const newRate = JSON.parse(event.body);
    var params = {
      TableName: 'InterestRates',
      Item: {
        'termlength' : {N: newRate["length"]},
        'InterestRate': {S: newRate["rate"]}
      }
    }; 
    
     let addNewRate = insertData(params);
     
    
     return  {
        statusCode: 200,
        body: JSON.stringify({ 
            response: addNewRate 
        })
   }
}

I also tried using Async/Await but it didn't work.我也尝试过使用 Async/Await,但没有成功。

You lambda function is Async but your code is not.你 lambda function 是异步的,但你的代码不是。 You need to await the completion of your function newRate which in turn should also await the function inserData which should also await your DDB request.您需要等待 function newRate的完成,而 function inserData也应该等待您的 DDB 请求。

I would advise you to do one of two things:我建议你做以下两件事之一:

  1. Learn how JS Async nature works and ensure you understand when you need to await.了解 JS 异步本质是如何工作的,并确保您了解何时需要等待。
  2. Use a synchronous programming language like Python/Boto3 where you will not run into such issues.使用像 Python/Boto3 这样的同步编程语言,你不会遇到这样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM