异步实现功能
Implement function in async
我想异步实现一个函数。此代码用于身份验证,如果用户已登录,则无法在没有登录的情况下访问该页面。我在 app.js 文件中的代码有效,有 isLoggedOut
函数,我可以在其中实现,所以这段代码有效,但我想将这段代码复制到我的 controller.js.
app.js中的工作代码:
app.get('/explore-random', isLoggedIn, (req, res) => {
const count = Recipe.find().countDocuments();
const random = Math.floor(Math.random() * count);
const recipe = Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
})
controller.js,我想实现isLoggedOut
函数到exploreRandom
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
function isLoggedOut(req, res, next) {
if (!req.isAuthenticated()) return next();
res.redirect('/home');
}
/**
* GET /explore-random
* Explore Random
*/
exports.exploreRandom = async (req, res) => {
try {
let count = await Recipe.find().countDocuments();
let random = Math.floor(Math.random() * count);
let recipe = await Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
} catch (error) {
res.status(500).send({message: error.message || "Error Occured"});
}
}
您可以简单地将导出的 exploreRandom
函数作为处理程序传递给您的 app.get
路由:
const exploreRandom = require('./path/to/explore-random-module');
app.get('/explore-random', isLoggedIn, exploreRandom);
我想异步实现一个函数。此代码用于身份验证,如果用户已登录,则无法在没有登录的情况下访问该页面。我在 app.js 文件中的代码有效,有 isLoggedOut
函数,我可以在其中实现,所以这段代码有效,但我想将这段代码复制到我的 controller.js.
app.js中的工作代码:
app.get('/explore-random', isLoggedIn, (req, res) => {
const count = Recipe.find().countDocuments();
const random = Math.floor(Math.random() * count);
const recipe = Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
})
controller.js,我想实现isLoggedOut
函数到exploreRandom
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
}
function isLoggedOut(req, res, next) {
if (!req.isAuthenticated()) return next();
res.redirect('/home');
}
/**
* GET /explore-random
* Explore Random
*/
exports.exploreRandom = async (req, res) => {
try {
let count = await Recipe.find().countDocuments();
let random = Math.floor(Math.random() * count);
let recipe = await Recipe.findOne().skip(random).exec();
res.render('explore-random', { title: 'Cooking Blog - Explore Random', recipe } );
} catch (error) {
res.status(500).send({message: error.message || "Error Occured"});
}
}
您可以简单地将导出的 exploreRandom
函数作为处理程序传递给您的 app.get
路由:
const exploreRandom = require('./path/to/explore-random-module');
app.get('/explore-random', isLoggedIn, exploreRandom);