0

My project is around a website on netlify, so i'm using netlify-lambda in this example.

I'm working with async/wait since i need to do a few calls to the database, keeping the code clean. When the exports handler is async, the callback function no longer works correctly. You will get Cannot read property 'statusCode' of undefined and the code will continue so your serverless function will crash with error "Write after end" so i have to return to give back the error msg or the success msg when the code is done.

But if i have to return from within another function/promise then i can't return the data to the previous function, it just crashes my api. I'm quite new to serverless functions, i litterally started using it yesterday. Any help would be appreciated :)

exports.handler = async function (event, context, callback) {
......More code
  mg.messages().send(email, function (error, body) {
    if (error) {
      return { statusCode: 500, body: error };
    } else {
      return { statusCode: 200, body: "Email var sendt" };
    }
  });
}
Henrik
  • 392
  • 2
  • 13
  • "But if i have to return from within another function/promise then i can't return the data to the previous function" — You aren't using a promise there. (Well, you are by using the `async` keyword, but that isn't a promise you can resolve in the callback you pass to `send`) – Quentin Jun 05 '20 at 13:35
  • Well look at the .....More code, i'm not showing everything. I'm using await on multiple database request – Henrik Jun 05 '20 at 13:36
  • Great. Use promises here too. – Quentin Jun 05 '20 at 13:37
  • Is await/async a no go in lambda? Should i just use promises? – Henrik Jun 05 '20 at 13:38
  • As far as I know await and async are fine (so long as you use a new enough version of Node for the lambda) – Quentin Jun 05 '20 at 13:38
  • Well i'm using the latest LTS build, isn't it possible to use async/await and still return from within another function. If it's fine, that means it supported right? So it must be possible to achieve the above in some way or form with async/await – Henrik Jun 05 '20 at 13:41
  • It isn't possible to return from a callback. See the duplicate. Use a promise. – Quentin Jun 05 '20 at 13:41
  • "to use async/await and still return from within another function. If it's fine, that means it supported right? So it must be possible to achieve the above in some way or form with async/await" — async and await are tools to manage promises. You can use them if you wrap the callback in a promise. – Quentin Jun 05 '20 at 13:41
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/215377/discussion-between-henrik-and-quentin). – Henrik Jun 05 '20 at 14:52

0 Answers0