如何将expression式parameter passing给nodejsasynchronous调用

这是我面临的问题。 在我的快递中间件的某处,我想检查文件的存在。

//Setting up express middeleware... app.use(f1); app.use(f2); ... function f1(req, res, next) { ... //Here I want to check if 'somefile' exists... fs.access('somefile', callback1, req, res, next); } //In the callback, I want to continue with the middleware... function callback1(err, req, res, next) { if (err) { //Report error but continue to next middleware function - f2 return next(); } //If no error, also continue to the next middleware function - f2 return next(); } function f2(req, res, next) { } 

如何将req,res作为parameter passing给fs.access的callback函数? 上面的代码不起作用。 我怀疑我需要使用闭包,但是如何?

一个完全不同的方式来看问题是:我如何使用,例如,fs.access本身作为一个明确的中间件function?

对我来说这种方法更有意义:

假设你想在f1中创build一个中间件,然后有一个中间件来处理handleError错误和其他中间件。

对于f1你已经有req,res在closures中,所以你将有访问fs.access的callback。

 function f1(req, res, next) { fs.access('somefile', (err) => { if (err) return next(err); // here you already have access to req, res return next(); } } function f2(req, res, next) { // do some stuff if there is err next(err); } function handleError(err, req, res, next) { if (err) { // handle somehow the error or pass down to next(err); } } app.use(f1); // you pass down the err | app.use(f2); // ------------ | app.use(handleError); // <----|