问题
I have come across two different ways to define express, use() middleware and am wondering if there is any difference between them or if it is simply syntax sugar?
A
const app = express();
app.use(cors());
app.use(responseTime());
app.use(someFunction);
app.use(anotherHandler);
app.use(failureHandler);
B
const app = express();
app.use(cors())
.use(responseTime())
.use(someFunction)
.use(anotherHandler)
.use(failureHandler);
回答1:
They are not two ways of using it. They are the same way. By calling app.use()
.
And it is not syntactic sugar either. app.use()
returns this
, hence the value it returns (which is the same value stored in app
) can be used to chain another call of .use()
and so on.
The result is the same; it's a matter of taste which way you prefer (you should use the one that you feel it's easier to read and understand).
回答2:
It's called method chaining:
Method chaining is a technique to simplify code in scenarios that involve performing multiple operations on the same object.
Looking into the source of Express.js and application:
app.use = function use(fn) {
...
return this:
}
As you can see use
returns this
hence chaining is possible.
回答3:
There is no real difference, only one is 3 characters shorter each time you want to write "app.use". It's kind of like definining .ejs and the naming files "home" instead of "home.ejs". The difference is that you finish the line each time using ;
app.use(cors());
with ;
is the end of the string.
For example if you used the below code, the .use(failureHandler);
wouldn't work because the ;
ends the first app.use
const app = express();
app.use(cors())
.use(responseTime())
.use(someFunction)
.use(anotherHandler); <------- STOPS HERE
.use(failureHandler)
They'll both work fine, but in my experience it would be more noticable missing 1
";" rather than each ";" on each line.
I would say it's just sugar syntax as you've mentioned.
来源:https://stackoverflow.com/questions/59668326/is-there-a-difference-between-these-two-methods-of-using-express-middleware