DEV Community


Discussion on: Basic Middleware Pattern in JavaScript

eomm profile image
Manuel Spigolon

Good explanation!

It would be interesting to cover async behaviour and issue like: what to do if a middleware call next when the following 2 other middleware already runs?

const pipe = Pipeline(
  (ctx, next) => { console.log(1); next(); setImmediate(next) },
  (ctx, next) => { console.log(2); next() }
  .then(() => { console.log('done') })
  .catch((err) => { console.log(err) })
muniftanjim profile image
Munif Tanjim Author • Edited

Each next function is supposed to be called only 1 time.

If you call it twice then, you get the Error('next() called multiple times') error.

Also, if you're using async middleware functions, you should always do await next().