node.js - Lambda 函数在完成之前退出

标签 node.js aws-lambda

我有一个非常简单的 Javascript lambda 函数,它从 dweet.io 获取 JSON 并将其存储在 DynamoDB 数据库中。但是,我在存储数据之前函数结束时遇到问题,并且我无法弄清楚我做错了什么。

函数

const http = require("http");
const AWS = require("aws-sdk");
let url = "http://dweet.io/get/latest/dweet/for/test";

exports.handler = async function (event) {
  const promise = new Promise(async function (resolve, reject) {
    http
      .get(url, (res) => {
        res.setEncoding("utf8");
        res.on("data", async function (chunk) {
          console.log("Body: ", chunk);
          var data = JSON.parse(chunk);
          console.log("Data:", data["with"][0]);
          await saveToDynamoDb(data["with"][0]);
          console.log("Done saving");
        });
        resolve(res.statusCode);
      })
      .on("error", (e) => {
        reject(Error(e));
      });
  });
  return promise;
};

async function saveToDynamoDb(data) {
  var dynamodb = new AWS.DynamoDB();
  var 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 requset: ", params);

  try {
    const data = await dynamodb
      .putItem(params, function (err, data) {
        if (err) {
          console.log("Error Saving:", err, err.stack);
        } else {
          console.log("Saving done:", data);
        }
      })
      .promise();
    console.log("Item entered successfully:", data);
  } catch (err) {
    console.log("Error: ", err);
  }

  return "ok";
}

函数日志

Function Logs
START RequestId: e7ebceff-560e-4a94-bc4f-3f1ae085d2ba Version: $LATEST
2021-10-15T03:40:15.217Z    e7ebceff-560e-4a94-bc4f-3f1ae085d2ba    INFO    Body:  {"this":"succeeded","by":"getting","the":"dweets","with":[{"thing":"test","created":"2021-10-15T03:38:03.138Z","content":{"lat":36.139095,"long":-115.30141,"speed":0,"head":357,"alt":840.1,"temp":31.81,"batt":4121}}]}
2021-10-15T03:40:15.245Z    e7ebceff-560e-4a94-bc4f-3f1ae085d2ba    INFO    Data: {
  thing: 'test',
  created: '2021-10-15T03:38:03.138Z',
  content: {
    lat: 36.139095,
    long: -115.30141,
    speed: 0,
    head: 357,
    alt: 840.1,
    temp: 31.81,
    batt: 4121
  }
}
2021-10-15T03:40:15.383Z    e7ebceff-560e-4a94-bc4f-3f1ae085d2ba    INFO    Save requset:  {
  Item: {
    item: { S: 'test' },
    time: { S: '1634269215382' },
    lat: { S: '36.139095' },
    long: { S: '-115.30141' },
    speed: { S: '0' },
    head: { S: '357' },
    alt: { S: '840.1' },
    temp: { S: '31.81' },
    batt: { S: '4121' }
  },
  ReturnConsumedCapacity: 'TOTAL',
  TableName: 'BoxTrackingEvents'
}
END RequestId: e7ebceff-560e-4a94-bc4f-3f1ae085d2ba
REPORT RequestId: e7ebceff-560e-4a94-bc4f-3f1ae085d2ba  Duration: 966.23 ms Billed Duration: 967 ms Memory Size: 128 MB Max Memory Used: 76 MB  Init Duration: 501.88 ms

Request ID
e7ebceff-560e-4a94-bc4f-3f1ae085d2ba

最佳答案

问题在于您正在“数据”事件回调完成之前解决。

resolve移动到回调中:

        res.on("data", async function (chunk) {
          console.log("Body: ", chunk);
          var data = JSON.parse(chunk);
          console.log("Data:", data["with"][0]);
          await saveToDynamoDb(data["with"][0]);
          console.log("Done saving");
          resolve(res.statusCode);
        });

导出函数的双重 promise 也可能存在问题:一个由 async 隐含,另一个来自返回的 promise 。我认为您可能想删除外部 async 关键字。

关于node.js - Lambda 函数在完成之前退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69579773/

相关文章:

node.js - 如何使用 Node.js + Express3 将变量注入(inject) EJS 模板?

javascript - 将带有预签名 URL 的分段上传从 aws javascript sdk v2 迁移到 v3

amazon-web-services - 是否可以在 Iot 规则调用的 Lambda 函数中检索主题名称

python - 在用于 python mssql 连接的 aws lambda 中未找到 pyodbc 模块

javascript - 在具有不同端口号的单个服务器上运行多个 sails 项目不起作用

javascript - 错误 : listen EACCES 0. 0.0.0 :80 OSx Node. js

javascript - waitFor() 找不到页面上显示的元素

java - 无法从AWS Lambda连接到RDS MySQL

amazon-web-services - 从 lambda(节点 js)发布 SNS 消息导致超时错误

python - 使用 python 的 Lambda@edge 函数