【问题标题】:Loading array into json, loading array back into program and using it globally with NodeJS将数组加载到 json 中,将数组加载回程序中并在 NodeJS 中全局使用它
【发布时间】:2020-06-29 02:28:58
【问题描述】:

所以我想要实现的是将包含对象的数组加载到 json 中,以便我可以将其解析回程序并在程序中的任何位置使用它。我已经尝试过使用 fs 的方式来执行此操作,但我很快发现当我阅读它时,我无法使用异步回调函数之外的变量。我在问是否有更好的方法将我的充满对象的数组加载到 json 中,读取它并能够在我的程序中的任何地方使用这些变量。我也想要一些见解,因为我想了解更多关于我是新手的主题,谢谢!

我的问题是我无法从异步回调函数访问变量,因为当我从函数本身调用它时它返回 undefined。

class Blockchain {
  constructor() {
    this.chain = [Blockchain.getGenesis()];
    console.log(Blockchain.getGenesis());
}
//further into the code with the issued function reading the data from .json to //place the objects into variables for the program to use
  static getGenesis(genChain) {
     fs.readFile(jsonRoute, 'utf-8', function(err, data) {
    if (err) throw err;

    jsonChain = JSON.parse(data);
    genesis = jsonChain.blocks[0].GENESIS_DATA;
    
    //console.log(genesis);
    
    /*console.log(jsonChain.blocks[0].GENESIS_DATA.lastHash); //specify element of where the object is and the field that you want to read*/
    
    /*jsonChain.blocks.push({
        GENESIS_DATA
    });

    console.log(jsonChain);
    
        fs.writeFile('CDSM/CDSM.json', JSON.stringify(jsonChain), 'utf-8', function(err) {
        if (err) throw err;
        console.log('Done!');*/
    });
    return genesis; //returns undefined since the variable I need to access gets //destroyed before I call it in the constructor (this is a multi module project //and need the array to "save" basically
}
    
}

.json 文件:

{"blocks":[{"GENESIS_DATA":{"timestamp":1,"lastHash":"v01d","hash":"?M=(((Position-1)=>ter)=>sen)=>non?","difficulty":20,"nonce":0,"data":[]}}]}

由于这种架构限制,我想问是否有不同的方式来读取 json 文件并将其内容引用到变量中。

【问题讨论】:

  • 您是在说加载.json 文件吗?原始数据来自哪里?请显示您尝试过的一些代码。
  • 将数据加载到采用数组的现有 .json 中。如果我向您展示我的旧代码,请不要尝试构建它,因为我要求不同的架构或不同的执行方式,因为我无法使用 fs 库访问回调异步函数中的变量。
  • 抱歉,我认为您对某些术语有些困惑,因此我很难理解您的意思。不过,我会尽力帮助你。你是说你只有一个对象数组,你想在代码的多个地方使用它们?
  • 我确信我混淆了术语,但我已经编辑了帖子,现在应该更有意义了
  • 啊,我明白了,这很有帮助。我会给你写一个解决方案。

标签: javascript node.js json database parsing


【解决方案1】:

由于getGenesis 是异步的,您需要让它返回一个Promise。 Promise 基本上只是一项将在未来某个时间完成的任务,它会等待结果并对其进行处理。

class Blockchain {
  constructor() {
    this.chain = [Blockchain.getGenesis()];
    console.log(Blockchain.getGenesis());
  }
  static getGenesis(genChain) {
    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);
      });
    });
  }
}

然后这样称呼它:

Blockchain.getGenesis(genChain).then(function(genesisData) {
  console.log(genesisData); // Genesis block data is here.
}, function(err) {
  // This only runs if there was an error.
  console.log(err);
});

resolvereject 只是两个函数,您可以调用它们来告诉 Promise 数据何时完成。如果请求成功,那么您使用数据调用resolve。如果有错误,您可以使用错误数据调用reject

Promise 类公开了then 方法,该方法简单地绑定了一个successerror 回调,以便在promise 完成时执行。

【讨论】:

  • 你太棒了,谢谢你的解释,很高兴从中学习,它也有效!
  • @NoobGuy 很高兴为您提供帮助!你可以用 Promises 做很多巧妙的事情,所以我建议你对它们做更多的研究。它们对于处理各种异步场景非常有用。
猜你喜欢
  • 2014-12-29
  • 2021-10-24
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多