Lambda函数无法稳定向DynamoDB写入数据求助
问题根源
你的代码核心问题是没有正确等待DynamoDB的异步写入操作完成,Lambda进程会在putItem的回调执行前就终止,导致数据写入失败;偶尔成功只是因为Lambda进程刚好没被立刻回收,属于巧合。
具体问题点:
insertData内部用了回调式的putItem,但函数本身同步返回status,此时回调还没执行,status永远是undefined,而且Lambda不会等待回调完成。- 虽然
handler标记为async,但调用newRate时没有await,newRate本身是同步函数,导致handler直接返回,Lambda进程提前结束。
修复方案
将异步操作改为Promise+Async/Await的形式,确保Lambda等待写入操作完成后再返回:
// 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) => { console.log(">>>> Running LoanInterestRates") if(event['resource'] == '/rates'){ if(event.httpMethod === 'POST'){ // 关键:await newRate,确保等待异步操作完成 return await newRate(event); } } // 处理其他情况的默认返回 return { statusCode: 404, body: JSON.stringify({response: "Invalid endpoint"}) } }; // 改为返回Promise的异步函数 async function insertData(params){ try { // 使用AWS SDK的promise()方法将回调式API转为Promise await ddb.putItem(params).promise(); return "Success"; } catch (err) { console.error("写入失败:", err); return "Error"; } } // 改为async函数,等待insertData的结果 async function newRate (event){ const newRate = JSON.parse(event.body); var params = { TableName: 'InterestRates', Item: { 'termlength' : {N: newRate["length"]}, 'InterestRate': {S: newRate["rate"]} } }; // 关键:await insertData,等待写入完成 let addNewRate = await insertData(params); return { statusCode: addNewRate === "Success" ? 200 : 500, body: JSON.stringify({ response: addNewRate }) } }
关键修改说明
insertData:改用ddb.putItem(params).promise()将异步回调转为Promise,并用try/catch捕获错误,返回对应的状态。newRate:标记为async,并await insertData的结果,确保等待写入完成后再返回响应。handler:调用newRate时加上await,保证Lambda不会提前终止。- 额外优化:根据写入结果返回不同的状态码(成功200,失败500),方便客户端判断结果。
内容的提问来源于stack exchange,提问作者Gustavo Iosimura
相关产品推荐
相关产品推荐

