Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS-serverless-express never resolving with promises

can anyone shed light on my issue opened at the aws-serverless-express repo on github? https://github.com/awslabs/aws-serverless-express/issues/276

I am trying to run my previous express.js server using the aws-serverless-express package. When running without any special options I resolve, but the promises in the chain are never respected, meaning I dont execute all things in the event loop.

If I run the serverlessexpress with 'PROMISE' flag, I execute all my promises, but the program never resolves and times out after the maximum time set.

I even started a new project as per the example in that repo, same result.

My main executing file (index.js) when resolving but not respecting my promises

const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app.js')
const server = awsServerlessExpress.createServer(app, null)

exports.handler = (event, context) => {
  return awsServerlessExpress.proxy(server, event, context)
}

My main executing file (index.js) when NOT resolving, but respecting my promises

const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app.js')
const server = awsServerlessExpress.createServer(app, null)

exports.handler = (event, context) => {
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE')
}

I also tried this:

const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app.js')
const server = awsServerlessExpress.createServer(app, null)

exports.handler = (event, context) => {
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise
}

My express server file (app.js)

const express = require('express')
const bodyParser = require('body-parser')
const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
const app = express()
const router = express.Router()

router.use(bodyParser.json())
router.use(bodyParser.urlencoded({ extended: true }))
router.use(awsServerlessExpressMiddleware.eventContext())

router.get('/', (req, res) => {
  res.render('index', {
    apiUrl: req.apiGateway ? `https://${req.apiGateway.event.headers.Host}/${req.apiGateway.event.requestContext.stage}` : 'http://localhost:3000'
  })
})

router.get('/users', (req, res) => {
  res.json(users)
})

const users = [{
  id: 1,
  name: 'Joe'
}, {
  id: 2,
  name: 'Jane'
}]

function myFunc () {
  console.log('hey')
}
setTimeout(myFunc, 3000)

app.use('/', router)

module.exports = app
like image 872
Simon Guldstrand Avatar asked Mar 18 '20 19:03

Simon Guldstrand


Video Answer


1 Answers

Make sure you are setting context.callbackWaitsForEmptyEventLoop to false

enter image description here

enter image description here read more about it here https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html

like image 56
naoufal bardouni Avatar answered Sep 22 '22 12:09

naoufal bardouni