l'esecuzione di funzioni in serie
-
14-10-2019 - |
Domanda
Prima di tutto ... Buon anno!
Potrebbe spiegare a me, come funziona? ho passato in rassegna throught Connetti 's ( https://github.com/senchalabs/connect ) il codice sorgente, ma io non capisco.
Vorrei scriverla da solo.
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?
// (...)
}
);
Grazie in anticipo!
Soluzione
Sembra come se il primo argomento della funzione che fornisci viene chiamata dalla funzione get()
prima.
Quando si chiama, 3 parametri sono forniti alla chiamata. All'interno della chiamata, il parametro req
deve essere un oggetto a cui è possibile assegnare le proprietà. Hai assegnato la proprietà var
, e dato un valore di 'Happy new year!'
.
L'argomento funzione successiva si passa viene chiamato tramite una chiamata al parametro next()
, e 3 parametri vengono nuovamente fornito alla chiamata. Il primo parametro è apparentemente lo stesso oggetto che è stato dato alla prima chiamata in cui è stata assegnata la proprietà var
.
Perché è (apparentemente) lo stesso oggetto, la proprietà si è assegnato è ancora presente.
Ecco un semplice esempio: http://jsfiddle.net/dWfRv/1/ (aprire la console)
// 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);
}
);
Si noti che questo è un esempio molto semplificato, con un minor numero di parametri nelle funzioni. Non ho cambiato anche che var
a msg
poiché var
è una parola riservata.
Altri suggerimenti
Se si vuole, provare a utilizzare il modulo asincrono. Rende cosa molto più facile essere in grado di eseguire in serie, paralleli o utilizzare una piscina.