La ejecución de funciones en serie
-
14-10-2019 - |
Pregunta
En primer lugar ... Feliz Año Nuevo!
¿Podría explicar a mí, ¿cómo funciona esto? I navegado throught Conectar 's ( https://github.com/senchalabs/connect ) el código fuente, pero yo no lo entiendo.
Me gustaría escribir por mí mismo.
app.get(
'/',
function(req, res, next) {
// Set variable
req.var = 'Happy new year!';
// Go to next function
next();
},
function(req, res, next) {
// Returns 'Happy new year!'
console.log(req.var); // <- HOW IS THIS POSSIBLE?
// (...)
}
);
Gracias de antemano!
Solución
Parece como si el primer argumento de la función que usted proporciona se llama a la función por primera get()
.
Cuando se le llama, 3 parámetros se proporcionan a la llamada. Dentro de la llamada, el parámetro req
debe ser un objeto al que se pueden asignar propiedades. Que ha asignado la propiedad var
, y le ha dado un valor de 'Happy new year!'
.
El siguiente argumento de la función que pase se llama a través de una llamada al parámetro next()
y 3 parámetros se proporcionan de nuevo a la llamada. El primer parámetro es aparentemente el mismo objeto que se le dio a la primera llamada en la que le asigna la propiedad var
.
Debido a que es (aparentemente) el mismo objeto, la propiedad que ha asignado todavía está presente.
Aquí está un ejemplo sencillo: http://jsfiddle.net/dWfRv/1/ (abrir la consola)
// The main get() function. It has two function parameters.
function get(fn1, fn2) {
// create an empty object that is passed as argument to both functions.
var obj = {};
// create a function that is passed to the first function,
// which calls the second, passing it the "obj".
var nxt = function() {
fn2(obj); //When the first function calls this function, it fires the second.
};
// Call the first function, passing the "obj" and "nxt" as arguments.
fn1(obj, nxt);
}
// Call get(), giving it two functions as parameters
get(
function(req, next) {
// the first function sets the req argument (which was the "obj" that was passed).
req.msg = 'Happy new year';
// the second function calls the next argument (which was the "nxt" function passed).
next();
},
function(req) {
// The second function was called by the first via "nxt",
// and was given the same object as the first function as the first parameter,
// so it still has the "msg" that you set on it.
console.log(req.msg);
}
);
Tenga en cuenta que este es un ejemplo muy simplificado, con un menor número de parámetros en las funciones. Tampoco que he cambiado var
a msg
desde var
es una palabra reservada.
Otros consejos
Si lo desea, intente utilizar el módulo asincrónico. Hace cosa mucho más fácil ser capaz de ejecutar en serie, paralelos o utilizar una piscina.