留学生辅导 express – When to use next() and return next() in Node.js – Stack Overflow

express – When to use next() and return next() in Node.js – Stack Overflow

Copyright By PowCoder代写 加微信 powcoder

Stack Overflow

Stack Overflow
Public questions & answers

Stack Overflow for Teams
Where developers & technologists share private knowledge with coworkers

Programming & related technical career opportunities

Recruit tech talent & build your employer brand

Advertising
Reach developers & technologists worldwide

About the company

current community

Stack Overflow

Meta Stack Overflow

your communities

Sign up or log in to customize your list.

more stack exchange communities

company blog

Collectives

Explore Collectives

Find a Job

Stack Overflow for Teams
– Collaborate and share knowledge with a private group.

Create a free Team
What is Teams?

Create free Team

Collectives on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more

When to use next() and return next() in Node.js

Ask Question

8 years, 8 months ago

5 months ago

This question shows research effort; it is useful and clear

This question does not show any research effort; it is unclear or not useful

Bookmark this question.

Show activity on this post.

Scenario: Consider the following is the part of code from a node web app.

app.get(‘/users/:id?’, function(req, res, next){
var id = req.params.id;
// do something
next(); //or return next();

Issue: I am checking which one to go with just next() or return next(). Above sample code works exactly the same for both & did not show any difference in execution.

Question: Can some one put light on this, when to use next() and when to use return next() and some important difference?

node.js express connect v8

Share a link to this question

Copy linkCC BY-SA 3.0

Follow this question to receive notifications

edited Mar 5 ’18 at 4:38

Amol M Kulkarni

asked May 29 ’13 at 9:39

Amol M KulkarniAmol M Kulkarni

19.9k3333 gold badges113113 silver badges162162 bronze badges

Add a comment

This answer is useful

This answer is not useful

Show activity on this post.

As @ ‘s answer:

If you don’t do it, you risk triggering the callback a second time later, which usually has devastating results

I give an example here if you write middleware like this:

app.use((req, res, next) => {
console.log(‘This is a middleware’)
console.log(‘This is first-half middleware’)

app.use((req, res, next) => {
console.log(‘This is second middleware’)

app.use((req, res, next) => {
console.log(‘This is third middleware’)

You will find out that the output in console is:

This is a middleware
This is second middleware
This is third middleware
This is first-half middleware

That is, it runs the code below next() after all middleware function finished.

However, if you use return next(), it will jump out the callback immediately and the code below return next() in the callback will be unreachable.

Share a link to this answer

Copy linkCC BY-SA 3.0

Follow this answer to receive notifications

answered Apr 14 ’17 at 2:01

PJCHENderPJCHENder

4,34222 gold badges1515 silver badges2424 bronze badges

As a beginner to express this answer made things clearer to me than the other answers. Thumbs up!

– mandarin

Dec 19 ’17 at 13:44

Would a similar thing be true of res.redirect(‘/’) vs. return res.redirect(‘/’) in this type of situation? Maybe it’s just better to always write return in front of res statements to avoid errors of setting headers after they were sent?

Sep 7 ’18 at 6:45

Why should I write code after next()? Isn’t it obvious that I do nothing after I finished my task in a middleware? @PJCHENder

Jul 25 ’19 at 6:17

@ImranPollob sometimes mistakes happens. When you write a lot of code, ifs/elses/etc. You may forget “`return next()`

Jul 25 ’19 at 16:45

Add a comment

This answer is useful

This answer is not useful

Show activity on this post.

Some people always write return next() is to ensure that the execution stops after triggering the callback.

If you don’t do it, you risk triggering the callback a second time later, which usually has devastating results. Your code is fine as it is, but I would rewrite it as:

app.get(‘/users/:id?’, function(req, res, next){
var id = req.params.id;

return next();

// do something

It saves me an indentation level, and when I read the code again later, I’m sure there is no way next is called twice.

Share a link to this answer

Copy linkCC BY-SA 3.0

Follow this answer to receive notifications

edited Apr 30 ’17 at 13:01

user6451184

answered May 29 ’13 at 10:53

14k44 gold badges4646 silver badges4949 bronze badges

Would a similar thing be true of res.redirect(‘/’) vs. return res.redirect(‘/’) in this type of situation? Maybe it’s just better to always write return in front of res statements to avoid errors of setting headers after they were sent?

Sep 7 ’18 at 6:46

@AdamD I would like to know that as well.

– theprogrammer

Sep 1 ’20 at 23:01

@theprogrammer Yes, I think this answer applies the same way to things like res.redirect and it would be best practice to use it, unless you have some other server tasks you want to do after redirecting the user.

Sep 4 ’20 at 1:47

Add a comment

This answer is useful

This answer is not useful

Show activity on this post.

next() is part of connect middleware. Callbacks for router flow doesn’t care if you return anything from your functions, so return next() and next(); return; is basically the same.

In case you want to stop the flow of functions you can use next(err) like the following

app.get(‘/user/:id?’,
function(req, res, next) {
console.log(‘function one’);
if ( !req.params.id )
next(‘No ID’); // This will return error
next(); // This will continue to function 2
function(req, res) {
console.log(‘function two’);

Pretty much next() is used for extending the middleware of your requests.

Share a link to this answer

Copy linkCC BY-SA 3.0

Follow this answer to receive notifications

edited May 1 ’17 at 10:07

answered May 29 ’13 at 11:01

drinchevdrinchev

18.3k33 gold badges6060 silver badges9191 bronze badges

Can we send parameter like: next(‘No ID’) ?

– Amol M Kulkarni

May 29 ’13 at 12:10

next(‘No ID’) is actually sending an error, which will break the flow.

– drinchev

May 29 ’13 at 12:15

Use next(null, “somevalue”); For tools like async.waterfall it will pass the value to the next function. For complex series of interactions that are data driven, I usually pass a context object between functions. That way I can create generic functions that can be shared across multiple end points and control flow via data in the context

– Chad Wilson

Oct 30 ’15 at 0:12

“so return next() and next(); return; is basically the same.” – just what I needed to read. thx @drinchev

Feb 25 ’16 at 1:25

I observe the opposite (when firing error): next(error) triggers next middleware, but continues to execute code; return next(error) just relegates execution to the next middleware. next(e) and return next(e) are NOT the same.

– Nickolodeon

Jul 25 ’18 at 17:06

Show 2 more comments

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com