0

Is there any kind of performance problem by returning a callback function in a async function as this code?:

import middy from '@middy/core';
import someFunction from 'someFunction';

async function testFunction (
  args,
  callback
) {
  // code
  const data = await someFunction();

  return callback(null, {
    statusCode: 200,
    body: JSON.stringify(data)
  });
}

export const handler = middy(testFunction);

I'm using Middy library, I don't think it's relevant to say but just in case.

5
  • 2
    You are not returning a callback function, you are executing a function named callback and returning its return value. Also, async is unneeded as you do not await. Commented Nov 13, 2020 at 22:04
  • 1
    "Middy allows you to return promises or throw errors from your handlers (instead of calling callback()) and middlewares (instead of calling next())." - that means you should use either. Not both. A function returning a promise with the result should never call a callback with that result. Commented Nov 13, 2020 at 22:09
  • @crashmstr you are right. I edited the question (I actually need async) Commented Nov 13, 2020 at 22:11
  • @Bergi that's what was I thinking (or something), I'm not sure how should I proceed Commented Nov 13, 2020 at 22:12
  • Just drop the callback and return the result directly. Commented Nov 13, 2020 at 22:18

1 Answer 1

1

You can return a promise or use callback.

const testFunction = async (event, context) => {
  // ... other logic
  return {
    statusCode: 200,
    body: JSON.stringify(data)
  }
}

This is a common pain point with new comers to middy. This has been addressed in middy v2 with the deprecation of callbacks altogether.

Sign up to request clarification or add additional context in comments.

2 Comments

middy v2? ahh good, that's pretty new github.com/middyjs/middy/tree/release/2.x
I wrote it over the holidays. I hope to have an alpha out this month.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.