fluency03
fluency03

Reputation: 2697

why Express does not implement Node.js style callbacks?

I have a question regarding the APIs. Why express does not implement Node.js style callbacks, i.e., Error-First Callbacks?

For example, router.METHOD:

router.get('/', function(req, res){
  res.send('hello world');
});

And furthermore, I also saw this Error handling:

app.use(function (err, req, res, next) {
  // logic
})

Then, my question is: after add the Error Handling middleware as above, can I regard my code as following?

router.get('/', function(err, req, res, next){
  res.send('hello world');
});

If so, I am able to use Q.denodeify converting the callback style to promise style right? Because Q.denodeify, as stated here, only deals with Node.js style (err, result) callback APIs

Upvotes: 0

Views: 68

Answers (2)

Dan Prince
Dan Prince

Reputation: 29989

An Express route handler can't be represented as a promise, because promises run once, whereas route handlers need to be run many times.

Express does actually use Node style callbacks whenever appropriate—e.g. next(err).

Then, my question is: after add the Error Handling middleware as above, can I regard my code as following?

You could, but you'd be defeating the point of error handlers in the first place. In the traditional Express app, when a request fails with an error, the route handlers after it can be safely skipped so that it can be passed to an error handler instead.

If you write all of your routes as error handlers then there's no semantic distinction between the parts of your code that handle success and the parts that handle failure. If a route handler throws or calls next(err) then the error will be passed to the next matching application route handler instead of to a dedicated error handler.

As a side note, this is more a question about Connect, the HTTP middleware implementation that Express is built on.

Upvotes: 3

Red8
Red8

Reputation: 1

It does, but in this case you are using routers and if you want to handle those errors you should declare error middleware at the end of the file. There is done() callback which takes first argument err and second done and this is the exact same callback style which node.js uses.

Upvotes: 0

Related Questions