You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript开发的AWS Lambda函数完成DynamoDB写入前提前退出问题求助

问题原因
  • 最核心的错误:你在http.get的回调里收到响应后立刻调用了resolve(res.statusCode),没有等待data事件里的saveToDynamoDb异步操作执行完成,Lambda拿到resolve的结果就直接结束运行,所以存储逻辑还没跑完函数就终止了,自然看不到后续的保存日志。
  • 其次,http响应的data事件可能会分多次触发,直接把单个chunk拿出来JSON.parse是不安全的,应该收集所有chunk拼接完成后再处理。
  • saveToDynamoDb函数里调用putItem时同时传了回调函数又调用了.promise(),属于冗余写法,不会影响运行但没有必要。
修复后的完整代码
const http = require("http");
const AWS = require("aws-sdk");
let url = "http://dweet.io/get/latest/dweet/for/test";

exports.handler = async function (event) {
  return new Promise(function (resolve, reject) {
    http.get(url, (res) => {
      res.setEncoding("utf8");
      // 收集所有响应块
      let rawData = '';
      res.on("data", (chunk) => { rawData += chunk; });
      // 等响应完全接收完成再处理
      res.on("end", async () => {
        try {
          console.log("Body: ", rawData);
          const data = JSON.parse(rawData);
          console.log("Data:", data["with"][0]);
          await saveToDynamoDb(data["with"][0]);
          console.log("Done saving");
          resolve(res.statusCode);
        } catch (err) {
          console.error("处理数据失败:", err);
          reject(err);
        }
      });
      res.on("error", (e) => reject(e));
    }).on("error", (e) => {
      reject(Error(e));
    });
  });
};

async function saveToDynamoDb(data) {
  const dynamodb = new AWS.DynamoDB();
  const params = {
    Item: {
      item: { S: data.thing },
      time: { S: "" + Date.now() },
      lat: { S: "" + data.content.lat },
      long: { S: "" + data.content.long },
      speed: { S: "" + data.content.speed },
      head: { S: "" + data.content.head },
      alt: { S: "" + data.content.alt },
      temp: { S: "" + data.content.temp },
      batt: { S: "" + data.content.batt },
    },
    ReturnConsumedCapacity: "TOTAL",
    TableName: "BoxTrackingEvents",
  };
  console.log("Save request: ", params);

  try {
    // 去掉冗余回调,直接用promise
    const res = await dynamodb.putItem(params).promise();
    console.log("Item entered successfully:", res);
  } catch (err) {
    console.log("Error saving to DynamoDB: ", err);
    throw err; // 出错抛出去让外层捕获
  }
  return "ok";
}
额外注意事项
  • 要确保Lambda执行角色已经配置了DynamoDB的putItem权限,否则保存会报权限错误。
  • 如果dweet.io返回的结构有变化,也要对应调整取值逻辑,避免解析报错。
  • 也可以直接用axios、node-fetch这类支持promise的HTTP请求库替代原生http模块,写法更简洁不容易出错。

内容的提问来源于stack exchange,提问作者Androme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 11:36:02