【发布时间】:2017-12-01 16:14:24
【问题描述】:
我很难理解接下来在这个 Express.js 示例中做什么以及为什么在这里使用它。
这是我处理路线的文件。
const express = require('express');
const controller = require('../controllers/myappcontroller');
const myroutes = express.Router();
const apphelper = require('../services/appservices/apphelper');
myroutes.get('/', apphelper.mycoolfunction, controller.index);
这是 apphelper.js 文件的内容
require('isomorphic-fetch');
function mycoolfunction(req, res, next) {
fetch('someurl')
.then((fetchRes) => {
return fetchRes.json();
}).then((jsonFetchRes) => {
res.locals.firstname = jsonFetchRes.contents.firstname[0].firstname;
next();
}).catch((err) => {
console.log(err);
res.locals.firstname = 'not available';
next();
});
}
module.exports = {
mycoolfunction: mycoolfunction,
};
为什么参数中有“next”,为什么要在函数中使用?是不是这样
【问题讨论】:
-
跳转到下一个中间件。如果你有
.get('/', func1, func2, func3),那么func1中的next()会跳转到func2,而func2中的next()会跳转到func3。 -
所以在这个例子中,如果我没有“下一个”,它会停在
res.locals.firstname= 'not available';并且不做任何其他事情?并且由于“next”的存在,它运行了行中的下一个参数,在这种情况下,controller.index对吗? -
是的,就是这样
-
太好了,非常感谢
标签: javascript node.js express