Async/await lambda function example

I was taking a look at the lambda function examples in the netlify-lambda github repo (you’ll have to scroll down a bit to see what I am referencing) and there seem to be two styles, the traditional callback style:

exports.handler = function(event, context, callback) {
// your server-side functionality
callback(null, {
  statusCode: 200,
  body: JSON.stringify({
    message: `Hello world ${Math.floor(Math.random() * 10)}`
  })
});
};

and the async/await style:

export async function handler(event, context) {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: `Hello world ${Math.floor(Math.random() * 10)}` })
  };
}

I tried out the traditional style and it works fine for me, but when I do the async/await style I get the error Function invocation failed: SyntaxError: Unexpected token 'export'.
Am I doing something wrong?

1 Like

I encountered the same problem, managed to get async/await working like this:

exports.handler = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: `Hello world ${Math.floor(Math.random() * 10)}` })
  };
}
1 Like

thanks for sharing your solution - @joshkmartinez, does this work for you?

Yes, his way works, I’ve been doing it in a similar way:

handler = async (event, context) => {
  return {
    statusCode: 200,
    body: "pong"
  };
};
exports.handler = handler;

The main thing was though if this example doesn’t work, why is it listed as one? I was really wondering if it was something I did wrong and it seems like the problem is with the example?

@joshkmartinez - firstly, glad it is working now. Secondly, that’s a valid question - as to why the example seems to not work for you. I’ll do some digging.

hi folks! the example works fine - IF you use netlify-lambda! that’s why it’s in the netlify-lambda repo. If you are NOT using netlify-lambda, and use the export syntax, you will get this exact error. If you want more function examples without netlify-lambda you can check the docs, or Functions examples - Netlify Functions or https://functions-playground.netlify.com/

One of the reasons netlify-lambda exists is because Node.js does not yet have ES modules support. ES modules syntax is the import and export syntax that you see me writing in there (note that this is different from the valid exports.functionName syntax above - confusing, i know). One of the express purposes of netlify-lambda is to allow people to write ES modules syntax, because it uses webpack underneath with a node target - hence copying an example directly from its readme without using the tool won’t work in “raw Node”.

Hope that makes sense and i’ll modify the readme to make clear.

2 Likes