Skip to content Skip to sidebar Skip to footer

Calling 'next()' From Promises In A Middleware Causes 'next Shouldn't Be Called More Than Once'

Recently I changed my code from Express to Restify. I'm honestly not sure if it used to happen before, but I guess it did. Basically in my middleware I call a promisified method an

Solution 1:

Change your chain to this:

somePromise().then(() => {
  next();
}, err => {
  // error occurred in somePromise()if(err.someatt) next();
  elsenext(err);
}).catch(err => {
  // error occurred in .then()'s next()// don't call next() again
});

The optional second argument of .then() acts as a .catch() callback, but is only invoked for errors thrown higher up in the chain, and is not invoked for errors thrown in the adjacent .then() callback.

A very helpful flowchart borrowed from this awesome answer demonstrates the difference between .then(onFulfilled, onRejected) and .then(onFulfilled).catch(onRejected):

promise thenpromise then-catch

Post a Comment for "Calling 'next()' From Promises In A Middleware Causes 'next Shouldn't Be Called More Than Once'"