Notes about asyncWrapper function

Note: This post is a details-post for the post: Learning web app development through free online tutorials – Organized Notes and Log, https://raviswdev.blogspot.com/2024/03/learning-web-app-development-through.html .

Router.get (or Router.METHOD generically) callback functions (multiple callbacks can be provided) take three arguments: req, res and optional argument next. From https://expressjs.com/en/5x/api.html#router.METHOD: router.get(‘/foo’, (req, res, next) => { –snip –})

In the tutorial code, initially at least the router.METHOD functions used do not specify the third and optional next argument. When the tutorial gets to the step of creating an asyncWrapper function, the asyncWrapper invokes the router.METHOD function with req,res and next even though the invoked function (at that stage in the tutorial) is defined as having only req and res arguments. It seems that JavaScript permits such function invocation with perhaps the third next argument being simply ignored while invoking the function. I need to confirm this.

… Confirmed … see code snippet below:

// this program confirms the above.
function fn(req, res) {
  console.log(req, res);
}
console.log('Invoking fn(req,res) with fn("req","res", "next")');
fn("req", "res", "next");
/* Program run output:
Invoking fn(req,res) with fn("req","res", "next")
req res
*/

-------- end code snippet ----------

Another related example code snippet:

// mytrycatchWrapper is passed an anonymous function (using arrow function syntax) that has only two arguments.
// But mytrycatchWrapper invokes it with three parameters (arguments). JavaScript runs it without complaints.
// It seems that the third parameter is just ignored.
function mytrycatchWrapper(fn) {
  return (req, res, next) => {
    try {
      fn(req, res, next);
    } catch (error) {
      console.log(error);
    }
  };
}
const x = mytrycatchWrapper((req, res) => {
  console.log(req, res);
});
x("req", "res", "next");
/* Program run output:
req res
*/

-------- end code snippet ----------

After using asyncWrapper I noted that I was getting 304 status code from Morgan for getting list of names in my test app:
GET /api/people 304 – – 81.593 ms
Note that 304 is Not Modified HTTP server response code.
But issuing GET /api/people from Postman gives status back as 200.
Adding a new entry to names resulted in following GET /api/people to return 200 with the data.
I guess some component of Express is returning 304 at times, as my code does not return 304.
Perhaps 304 was being returned at times even before adding asyncWrapper but I had simply not noted it. 

Comments

Archive