【发布时间】:2020-10-18 03:09:25
【问题描述】:
所以当涉及到 nodejs 时,我在范围方面遇到了一些问题。我想知道如何在全局空间中初始化变量,在函数(私有范围)中对其进行初始化,然后在类中的任何位置调用它时使其等于在私有范围中初始化它的值。我注意到的一件事是,尽管您可以在私有范围内使用该变量,但当在该函数之外再次调用它时,它只是变为未定义。如何返回私有时初始化的相同函数?这不是我发布的代码,而是一个示例,以防图片不清晰
let name;
class blah {
static blablah() {
name = josh;
}
console.log(name);
//this will return undefined and not josh
}
在我的上下文中我需要什么:
let genesis;
let jsonChain;
class Blockchain {
constructor() {
//this.chain = [Blockchain.getGenesis()];
console.log(Blockchain.getGenesis());
}
//down the file we find the issued function...
static getGenesis() {
fs.readFile(jsonRoute, 'utf-8', function(err, data) {
if (err) throw err;
jsonChain = JSON.parse(data);
genesis = jsonChain.blocks[0].GENESIS_DATA;
return genesis;
});
//returning here instead inside the callback also yields undefined
//I want to be able to access my contents from json file through
//the genesis variable which is global when I return this function
//but I cannot reach the contents of the callback
}
}
解决方案:确保返回承诺,以便异步函数稍后在您调用它时在您的程序中运行。
let genesis;
let jsonChain;
class Blockchain {
constructor() {
this.chain = [Blockchain.getGenesis()];
console.log(Blockchain.getGenesis().then(function(genesisData) {
console.log(genesisData); // Genesis block data is here.
}, function(err) {
// This only runs if there was an error.
console.log(err);
}));
}
//down the file we find the solved function...
static getGenesis() {
return new Promise(function(resolve, reject) {
fs.readFile(jsonRoute, 'utf-8', function(err, data) {
if(err) return reject(err);
const jsonChain = JSON.parse(data);
resolve(jsonChain.blocks[0].GENESIS_DATA);
});
});
}
}
module.exports = Blockchain;
【问题讨论】:
-
你没有在任何地方显示你实际调用你的
blablah()方法。而且,您的console.log(name)试图在类定义中,但不是在没有意义的方法中。而且,josh不是一个定义的值。 -
我们可以从您尝试在下面的评论中粘贴的代码中看到,真正的问题是您正在尝试从异步回调更新更高范围的变量。除了是一个糟糕的设计原则之外,您无法从回调外部知道全局何时更新。您可能会尝试在更新之前访问全局。无论如何,这只是一种反模式。不要那样做。使用异步回调中的值或从该回调中调用一个函数并将该值传递给该函数。这就是你异步编程的方式。
-
请显示您调用
getGenesis()的代码,并显示您尝试使用jsonChain变量的代码。这将阐明实际问题(如我之前的评论中所述),并将允许我们就您应该如何做提供建议。 -
另外,永远不要在一个普通的异步回调中使用
if (err) throw err(这是另一种反模式)。这没有任何用处。你需要真正的错误处理。 -
感谢您的洞察力,我需要稍后再回来解决此问题,因为我有强制性工作要做。但是非常感谢您的洞察力,我学到了很多东西!
标签: javascript node.js variables scope global-variables