Node.js serverless offline hangs after 1st request

1.3k Views Asked by At

first time when i make a request its working fine, but when i make the request again without restarting the server, its going time out and returning some promise error

following is the code and error

module.exports.getOne = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;

  db.once('open', () => {
      Client.findOne({name:{ $regex : new RegExp(event.pathParameters.name, "i") }})
        .then(client => callback(null, {
          statusCode: 200,
          body: JSON.stringify(client)
        }))
        .catch(err => callback(null, {
          statusCode: err.statusCode || 500,
          headers: { 'Content-Type': 'text/plain' },
          body: 'Could not fetch the note.'
        }))
        .finally(() => {
          // Close db connection or node event loop won't exit , and lambda will timeout
          db.close();
        });
    });
};

Error:

(node:3273) UnhandledPromiseRejectionWarning: Error: Cannot stop server while in stopping state
1

There are 1 best solutions below

0
On

The issue is that you aren't completing the call by calling callback so it thinks that your getOne() function isn't finished.

Take a look at the sample code that serverless provides when you setup a new serverless app with their template

module.exports.hello = (event, context, callback) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless v1.0! Your function executed successfully!',
      input: event,
    }),
  };

  callback(null, response);
};