繁体   English   中英

回调函数的参数如何在JavaScript Node.js中工作

[英]How the parameters of callback function work in javascript nodejs

当我们调用异步函数时,是否可以传递带有参数的回调函数。 我无法理解我需要记住回调函数中参数的顺序。 例如快递

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

如何知道参数的数量以及它们包含的内容,因为我看了一个教程,所以我先知道要求,然后知道res。

当我们调用异步函数时,是否可以传递带有参数的回调函数。

取决于功能。 现代的倾向于返回Promise而不是接受回调。

我需要记住回调函数中参数的顺序吗?

不,您可以查找它们。

如何知道参数的数量及其包含的内容

通过阅读该函数的文档,您可以将回调传递给

app.get或任何app。[CRUD方法]以相同顺序接受2或3个参数( requestresponsenext )。 下一个可选的

尝试运行此代码。 在我们进入get方法之前,您可以看到有2个中间件函数(像函数数组一样传递)。 get方法之后的另一个中间件。 这将使您对处理请求的顺序方式以及如何处理请求有基本的了解。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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