node.js - 如何从 NodeJS Lambda 函数中的 axios.get 等异步函数获取返回值?

标签 node.js amazon-web-services asynchronous aws-lambda axios

我正在使用 AWS Amplify 在 AWS 中构建一些后端功能,并且我有一个由 DynamoDB 更新触发的 Lambda 函数。它不需要返回任何东西。

我在 CloudWatch 中不断收到错误,提示“SyntaxError:await 仅在异步函数中有效”。是否有另一种方法可以在处理程序中运行这些异步函数?

exports.handler = async (event) => {
  console.log(JSON.stringify(event, null, 2));
  event.Records.forEach(record => {
    console.log(record.eventID);
    console.log(record.eventName);
    console.log('DynamoDB Record: %j', record.dynamodb);

    if (record.eventName == "INSERT") {
      try {
        res = await axios.get("https://google.com", {});
        console.log(res);
      }
      catch(e){
        console.log(e);
      }
    }
  });
};

最佳答案

您正在 forEach 循环内执行等待,这是它自己的函数状态。您可以尝试在 if 语句中使用内联异步等待函数

(async function process() {
    try {
        res = await axios.get("https://google.com", {});
        console.log(res);
    }
    catch(e){
        console.log(e);
    }
}())

关于node.js - 如何从 NodeJS Lambda 函数中的 axios.get 等异步函数获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63302159/

相关文章:

javascript - 如何替换node.js REDIS中已弃用的HMSET

php - AWS S3、速度和服务器负载

amazon-web-services - 如何使用Ansible的iam_module获取访问 key ?

node.js - 如何解决 Pug 中 Json 数组的迭代问题

javascript - Node.js http2 服务器与一个域的 http 服务器

javascript - 将全局变量的值赋给对象

ruby-on-rails - 没有这样的文件或目录(public/assets/manifest*)

python - 运行两个异步函数而不互相阻塞

javascript - Async/await - 等待函数和非等待函数的组合

java - Java如何保证ListenableFuture中future.isDone()时回调被调用