Bert Deterd
Bert Deterd

Reputation: 1794

Async function in express middleware: unhandledRejection - response is not defined

I keep getting the error : UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ReferenceError: response is not defined

I have an express middleware like this (simplified):

 const myMiddleware = require('./mymiddleware');
 router.use(myMiddleware);

Then in the file ./mymiddleware.js

module.exports = setup;

function setup(req, res, next) {
  try {
    execute()
      .then(data => {
        req.host = data;
        console.log(data);
        next();
      })
      .catch(() => {});
  } catch (e) { next('error') }
}

async function execute() {
  try {
    const host = getHost();
    ......
    return host;

  } catch (e) {
    return new Error("x");
  }
}

I want the async function to handle some promises with the await feature. I see the then / console.log(data) being called but then the error as mentioned is triggered.

can async functions be used with express middleware?

Regards, Bert

Upvotes: 0

Views: 1064

Answers (2)

Bert Deterd
Bert Deterd

Reputation: 1794

I installed a previous version of node.js ( 8.9.0 > 7.6.0 ).

I can install the package now.

When a new release of @sap/xssec comes out I will update the node version and see if it is fixed

Upvotes: 0

Shiv Kumar
Shiv Kumar

Reputation: 1114

You have made a typo in second line you have written mymiddleware instead of writing myMiddleware.

Incorrect code

 const myMiddleware = require('./mymiddleware');<br>
 router.use(mymiddleware);

correct code

 const myMiddleware = require('./mymiddleware');<br>
 router.use(myMiddleware);

Upvotes: 3

Related Questions