简体   繁体   中英

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. eg 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.

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

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

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM