From f4c06e5fc9bc27baa25fd4ceab0c24724767464f Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Tue, 5 Dec 2017 23:12:41 -0800 Subject: [PATCH] docs(middleware): suggest using `return next()` to stop middleware execution Fix #5866 --- docs/middleware.jade | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/middleware.jade b/docs/middleware.jade index a4a4779ae5b..2d1222e5d0d 100644 --- a/docs/middleware.jade +++ b/docs/middleware.jade @@ -50,13 +50,29 @@ block content There are two types of `pre` hooks, serial and parallel. h4#serial Serial :markdown - Serial middleware are executed one after another, when each middleware calls `next`. + Serial middleware functions are executed one after another, when each + middleware calls `next`. :js var schema = new Schema(..); schema.pre('save', function(next) { // do stuff next(); }); + :markdown + The `next()` call does **not** stop the rest of the code in your middleware function from executing. Use + [the early `return` pattern](https://www.bennadel.com/blog/2323-use-a-return-statement-when-invoking-callbacks-especially-in-a-guard-statement.htm) + if you want to stop execution when you call `next()`. + :js + var schema = new Schema(..); + schema.pre('save', function(next) { + if (foo()) { + console.log('calling next!'); + // `return next();` will make sure the rest of this function doesn't run + /*return*/ next(); + } + // Unless you comment out the `return` above, 'after next' will print + console.log('after next'); + }); h4#parallel Parallel p | Parallel middleware offer more fine-grained flow control.