最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

启动应用程序时对象返回初始值

运维笔记admin12浏览0评论

启动应用程序时对象返回初始值

启动应用程序时对象返回初始值

当我的应用启动应用时,我的变量之一返回初始值。这是我的代码

routes.js

router.post("/build-envEP", (req, res, next) => {
    consts.setNewConst("env", req.body.env);
    console.log(consts.getConsts().env); // returns what I expect
    res.status(201).type('application/xml').send(operations.xml);
});

constants.js

var consts = {};

module.exports.setNewConst = function(key, value){
    return consts[key] = value;
}

module.exports.getConsts = function(){
    return consts;
}

builder.js

...

console.log(consts.getConsts().env)

...

启动服务器时,我得到了{}

这里是我的控制台输出:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
undefined

有时我得到undefined,有时我得到{}

谢谢您的任何建议!

回答如下:

您需要将contants.js更改为:

var consts = {
  setNewConst: function(key, value) {
    return (consts[key] = value);
  },

  getConsts: function(key) {
    return this[key];
  }
};

module.exports = consts;

var consts = {
  setNewConst: function(key, value) {
    return (consts[key] = value);
  },

  getConsts: function(key) {
    return this[key];
  }
};

consts.setNewConst("a", 10);

const result = consts.getConsts("a");

console.log(result);
发布评论

评论列表(0)

  1. 暂无评论