How to use express-async-handler - node.js

I am going through some code on github: https://github.com/linnovate/mean/blob/master/server/routes/user.route.js
But there is a portion of it I don't understand, that is:
router.route('/')
.post(asyncHandler(insert));
On npm express-async-handler
is described as:
Simple middleware for handling exceptions inside of async express routes and passing them to your express error handlers.
They go give an example of how to use the module, but it doesn't explain much.
So my questions are:
How is the insert function on line 12 called without parentheses?
What is the function of asyncHandler(), what would the code look like if you decide on not using it?
Normally when using router.route('/').post there are curly braceswhich follow. In this code I cant see any. So my question are: Is the async function insert part of the function body of router.route('/').post? and if not then why are there no curly braces?
What exactly is being exported here user.controller.js on line 14 (is it an object, a var...)? What is the advantage of exporting it this way? Why not just export the function insert()?
Thank you in advance.

How is the insert function on line 12 called without parentheses?
The insert function is not called here. It is passed to asyncHandler() as a function reference so it can be called later. It is asyncHandler() which is called immediately and that returns a new function that is passed to .post() as the request handler.
What is the function of asyncHandler(), what would the code look like if you decide on not using it?
This is a wrapper around insert that looks for a rejected promise returned from the function and, if found, calls next(err) automatically.
Normally when using router.route('/').post there are curly braceswhich follow. In this code I cant see any. So my question are: Is the async function insert part of the function body of router.route('/').post? and if not then why are there no curly braces?
I'm not sure what you mean by curly braces. .post() expects a function reference to be passed to it that will be called with a certain set of parameters when the defined route matches an incoming request. It can use as either of these:
// externally defined request handler function
router.route('/').post(someRequestHandlerFunc);
// inline defined request handler function
router.route('/').post(function(req, res, next) {
// code here for the request handler
});
What exactly is being exported here user.controller.js on line 14 (is it an object, a var...)? What is the advantage of exporting it this way? Why not just export the function insert()?
I'm assuming the line 14, you're asking about is here. That's just exporting the insert function on the insert property of this modules exports. When you export a function, you don't use insert(). That calls the function immediately. You just refer to the function's name as insert to export a reference to the function that can be called later.
The reason to export is as a property of an object rather than just export the single function is to make the module extensible so it can export other things as different named properties.

Related

Command not found on a funciton calling from another [duplicate]

In the script below, does the order in which items are declared matter?
For example, if the add_action points to a function that has not yet been defined? Does it matter or should the function declaration always precede any code in which its called?
add_action('load-categories.php', 'my_admin_init');
function my_admin_init(){
//do something
}
That doesn't matter if the function is declared before or after the call but the function should be there in the script and should be loaded in.
This is the first method and it will work:
some_func($a,$b);
function some_func($a,$b)
{
echo 'Called';
}
This is the second method and will also work:
function some_func($a,$b)
{
echo 'Called';
}
some_func($a,$b);
From the PHP manual:
Functions need not be defined before they are referenced, except when a function is conditionally defined as shown in the two examples below.
However, while this is more of a personal preference, I would highly recommend including all the functions you actually use in an external functions.php file then using a require_once() or include_once() (depending on tastes) at the very top of your main PHP file. This makes more logical sense -- if someone else is reading your code, it is blindingly obvious that you are using custom functions and they are located in functions.php. Saves a lot of guesswork IMO.
you can call a function before it's defined, the file is first parsed and then executed.
No.
It is not C :P...
As you can see here , the whole file is first being parsed and then executed.
If a function that doesn't exist is being called, php will throw an error.
Fatal error: Call to undefined function
As per my personal experience, In some special cases (Like, passing array's in function or function inside a function and so on). It's best option to define the function above the call. Because of this sometimes neither function works nor PHP throw an error.
In normal php functions, it doesn't matter. You can use both of the types.
It does not matter, as long as it is declared somewhere on the page.
as seen here:
http://codepad.org/aYbO7TYh
Quoting the User-defined functions section of the manual :
Functions need not be defined before
they are referenced, except when a
function is conditionally defined
So, basically : you can call a function before its definition is written -- but, of course, PHP must be able to see that definition, when try to call it.

TypeError: next is not a function when io.use(passport.authenticate('google'))

I am trying to use authentication with socket.io's io.use() as they've mentioned in their documentation. They seem to have an example of io.use() in which the function calls next(), but I am getting the error:
TypeError: next is not a function
for using using io.use(passport.authenticate('google'))
Update
I know that the documentation shows that I need to pass next as an argument. But I cannot pass next, because the passport.authenticate() method is defined by passport.js, I am not declaring it there (like in the docs).
The only option I think I can use is defining a function and using passport.authenticate inside it. But I am not sure if that would be the correct way to go. I may also need to handle custom callback if I do so.
You need to pass next as an argument

Does the middleware of mongoose also refer to the middleware of express?

I'm just trying to get a grasp of what middleware refers too. At first I thought it was functions used in the framework express. Although now I'm getting a sense that they simply just refer to functions that get in the middle between asynchronous functions.
I know it's common to see next() get used to move from one middleware to the next. Both express and mongoose have the next() call with similar names. I'm concerned as I don't see mongoose or express refer to each other in their documentation. So this leaves me to believe the context of their middleware is just for themselves.
http://mongoosejs.com/docs/middleware.html
http://expressjs.com/en/resources/middleware.html
When combining express with mongoose are all the middlewares lined up together/concatenated or is it separate?
e.g. together/concatenated
- calling next() on mongoose will also trigger expresses middleware function
e.g. Separate
- mongoose just has it's middleware next() just move for pre/post hooks
- express also just has it's middleware next() just move towards it's supported middleware functions
Short answer: they're separate.
Longer answer: By convention, most middleware stacks implement some kind of next function to call in order to proceed down the stack and call each middleware function in turn.
It's a matter of scope. Express and Mongoose both have their own independent middleware stacks, so what the next function does depends on where it gets called. As a general rule of thumb, every function-- including the anonymous functions used for callbacks that accept a next parameter-- have their own scope.
Consider the following really brief example of differently scoped, but otherwise identical parameter names:
function doSomething(arg) {
console.log(arg)
function doSomethingElse(arg) {
console.log(arg);
}
doSomethingElse('different');
}
doSomething('original');
// Outputs
// > 'original'
// > 'different
Even though doSomething and doSomethingElse both have a parameter called arg, the value logged to the console by doSomethingElse is the value actually passed to that function-- the value of arg as scoped to the function it was called in, not the scope surrounding it.
This is true for Mongoose middleware applied within Express middleware (or vice-versa): they just happen to share a similar, conventional parameter name.
As a learning experiment, you should deviate from conventions for a moment (but not forever; conventions exist for a reason!) to name your Express and your Mongoose next parameters something else in a single file-- expressNext and mongooseNext, perhaps-- to help differentiate them in your mind.

How to call callback function in another callback function in node.js

How to call callback function in within callback function in node.js
callbacks are simply parameters in JS, just like others
just pass it to other functions
also notice that JS is lexical scoping
so make sure ur callback parameter in the scope or outer scope
--> What is lexical scope?
Call back functions in node js are no different than those in javascript. This is one way you can call it.
function someFunction(callback){
callback(params);
}
the call back function can be defined as any normal function.For example
function random(number){
return Math.random()};
the function someFunction can now be called as
someFunction(random);
That's it.The important thing to understand here is that node js is still javascript.So everything trick that works in javascript will work in node js.

Directly calling a function bound to the exports object

I'm reading the cluster.js file of the cluster package and this part confuses me:
fs.readdirSync(__dirname + '/plugins').forEach(function(plugin){
plugin = plugin.replace('.js', '');
exports.__defineGetter__(plugin, function(){
return require('./plugins/' + plugin);
});
});
I know that you can bind objects or functions to the exports object to expose them to different files, but it seems that it is calling a function already bound to the object. However, I always thought you needed to require the file and access functions that way. What is going on here?
This is realization of lazy loading for plugins. Plugin will be loaded only after first access to module property with his name. __defineGetter__ is the 'syntax sugar' not presented in ECMAScript standard. It binds an object's property to a function to be called when that property is looked up.
If a module sets exports to a single function rather than an arbitrary object, then the result of require will be a function reference which can be called directly (note that a function is actually a type of object and as such can have properties, which can also be functions).
That's not what's going on here, though. At the time the code you've shown is executed, a function called __defineGetter__ has already been defined and attached to exports. Here it's simply being called as a method of exports (presumably because the author didn't feel the need to create a redundant local name for it).
i.e. somewhere along the line there's something like
exports.__defineGetter__ = function(propname, getter) {
...
}
Since it doesn't have a local name, the only way to call it is through exports.
Obviously the purpose of the code here is to allow you to call cluster.nameOfPlugin.method(...) without having to manually require each plugin, while not requiring all the possible plugins to be preloaded; instead only the ones you actually use get loaded.

Resources