【问题标题】:How can I get a return from an async function like axios.get in a NodeJS Lambda function?如何从 NodeJS Lambda 函数中的 axios.get 等异步函数获得返回?
【发布时间】:2020-11-27 19:30:19
【问题描述】:

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

我在 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);
      }
    }
  });
};

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 噢!这绝对是问题所在。但是,我注意到更改为这个会引入一个新错误。我无法再从 dns.resolve 函数获取值 - 我的函数现在看不到它修改的任何变量。它在 foreach 中有效,但不再有效
    • 我必须查看代码才能解决问题所在。
    猜你喜欢
    • 2015-04-21
    • 2018-01-03
    • 2017-12-09
    • 2017-08-08
    • 1970-01-01
    • 2013-09-27
    • 2020-03-04
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多