ShIvam Rawat
ShIvam Rawat

Reputation: 61

How the parameters of callback function work in javascript nodejs

When we call an asynchronous function if we can pass a callback function with parameters. I am unable to understand that do I need to memorize the order of the parameter in the call back function. e.g in express

app.get('/',function(req,res))

How to know the number of the parameters and the what they contain because I watched a tutorial and I know first req and then res.

Upvotes: 0

Views: 1347

Answers (3)

sairohith
sairohith

Reputation: 392

Try to run this code. You can see there are 2 middleware functions before we get inside the get method(Passed like array of functions). Another middleware after the get method. This will give you a rudimentary understanding of the sequential way request gets handled and how request can be manipulated.

var express = require("express");
var app = express();
var port = 3000;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));



var middleware1 = function(req,res,next){
  console.log("Before Get method middleware")
  console.log("middleware1");
  next();
}
var middleware2 = function(req,res,next){
  console.log("middleware2");
  next();
}

app.get("/", [middleware1 , middleware2],(req, res, next) => {
    console.log("inside Get middleware")
    req['newparam'] = "somevalue"; // or somecode modiffication to request object
    next(); //calls the next middleware
});

app.use('/',function(req,res){
  console.log("After Get method middleware")
  console.log(req['newparam']); //the added new param can be seen
  res.send("Home page");
})


app.listen(port, () => {
    console.log("Server listening on port " + port);
});

Upvotes: 1

sairohith
sairohith

Reputation: 392

app.get or any app.[CRUD Method] takes 2 or 3 params (request, response, next) in the same order. The next is optional

Upvotes: 0

Quentin
Quentin

Reputation: 943217

When we call an asynchronous function if we can pass a callback function with parameters.

Depends on the function. Modern ones tend to return a Promise instead of accepting a callback.

do I need to memorize the order of the parameter in the call back function.

No, you can look them up.

How to know the number of the parameters and the what they contain

By reading the documentation for the function you are passing the callback to

Upvotes: 1

Related Questions