首页 > 解决方案 > 为什么将 console.log() 放置在呈现视图的函数中时会重复打印一个变量?

问题描述

我有一个简单的全局变量,它在我的app.js文件中保存一个字符串:

global.MyActivity = "peanutbutterjellytime"

我有另一个文件index.js是路由器/控制器。在这个文件中,我这样做:

var router = require('express').Router();
console.log(global.MyActivity); // this prints the variable once to the console. Great!

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints the variable in duplicate
    res.render('index', {pagetitle: 'Activity Page'}); // i think this is causing the problem. if i remove it it works fine
});

module.exports = router;

我总是注释掉方法的console.log(global.MyActivity);外部,router.get()所以我知道它不会因为任何附加而重复打印。

我不明白为什么在渲染视图时,控制台会两次打印变量,而如果我删除该渲染代码,它会正确执行并且只打印一次。所以这很好用:

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints once
    console.log("I am sync"); // this prints once
});

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints twice!
    console.log("I am async"); // this prints twice!
    res.render('index', {pagetitle: 'Activity Page'}); 
});

如果我想发送global.MyActivity到我的视图,这会给我带来一个问题,res.render('index', {pagetitle: 'Activity Page', activity: global.MyActivity})因为它是重复的。我的视图引擎是 express-handlebars,它只是用于 Express 的 Handlebars.js。

更新/修复 1(侥幸,我不明白它为什么起作用) 只是为了踢我放入一个回调函数。这解决了重复控制台日志的问题,但视图永远不会呈现。

router.get('/', async function (req, res) {
    console.log(global.MyActivity); // this prints once now! why?

    res.render('index', {pagetitle: 'Activity Page'}, function(){ }); // this never renders 

});

标签: javascriptnode.jsexpresshandlebars.jsexpress-handlebars

解决方案


推荐阅读