How can I get a return from an async function like axios.get in a NodeJS Lambda function?

Viewed 364

I am using AWS Amplify to build some backend fun in AWS, and I have a Lambda function that is triggered from an update to DynamoDB. It doesn't need to return anything.

I keep getting errors in CloudWatch saying "SyntaxError: await is only valid in async function". Is there another way to run these async functions within the handler?

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);
      }
    }
  });
};
1 Answers

you are performing an await inside of a forEach loop which is it's own function state. You could try an inline async await function inside the if statement

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