首页 > 解决方案 > 为什么这些变量不能保持价值?

问题描述

我有两个问题我无法弄清楚。当我首先调用 GetParams 以从文本文件中获取使用的定义值时,首先调用它之后的代码行,或者在我从函数中取回数据之前将其报告给控制台。在该函数中收集的任何数据都是无效的。变量显然被分配了数据,但在函数调用之后它消失了。

let udGasPrice = 0;
let udGasLimit = 0;
let udSlippage = 0; 

我想从文本文件中获取数据并将其分配给需要全局的变量。可以在函数中赋值,但在函数之外使用。所以上面是我在函数之外声明它们的方法。因为如果我在里面声明它们,我就会失去作用域。用 0 声明然后重新分配似乎不正确,但我还能如何声明它们 gloabaly 以由另一个函数操作?

接下来,调用该函数的代码来完成工作

GetParams();
console.log('udGasPrice = " + udGasPrice );

GetParams 之后的代码报告 0 但在函数内部值是正确的

数据在函数内部被读取并明确分配。它既不漂亮也不聪明,但它确实有效。

function GetParams()
{
  const fs = require('fs')

  fs.readFile('./Config.txt', 'utf8' , (err, data) => {
    if (err) {
      console.error(err)
      return;
    } 
    // read file contents into variable to be manipulated
    var fcnts = data;
    let icnt = 0;   
    
    for (var x = 0; x < fcnts.length; x++)    {
      var c = fcnts.charAt(x);
     //find the comma
      if (c == ',') {
         // found the comma, count it so we know where we are.
         icnt++;
         if (icnt  == 1 ) {
             // the first param
             udGasPrice = fcnts.slice(0, x);             
             console.log(`udGasPrice = ` + udGasPrice);
         } else if (icnt == 2 ) {
            // second param
            udGaslimit = fcnts.slice(udGasPrice.length+1, x);
            console.log(`udGaslimit  = ` + udGaslimit);
         } else {
             udSlippage = fcnts.slice(udGaslimit.length + udGasPrice.length +2, x);          
             console.log(`udSlippage  = ` + udSlippage );
         }       
      }       
    }   
})
}

就像我说的我知道算法很差,但它有效。(我很菜鸟)但为什么变量没有保留值,为什么 GetParams() 之后的代码首先执行?感谢您的时间。

标签: javascriptnode.js

解决方案


代码在 GetParams 方法完成之前执行,因为它所做的是异步工作。您可以通过在读取文件时使用回调函数来看到这一点。

作为最佳实践,您应该向 GetParams 提供回调并使用文件中的结果调用它,或者通过采用 Promise 和(可选)async/await 语法来使用更现代的方法。


推荐阅读