genDis
genDis

Reputation: 11

Why are these variables not maintaing value?

I have two problems i cant figure out. When i call GetParams first to get used defined values from a text file, the line of code after it is called first, or is reported to the console before i get data back from the function. Any data gathered in that function is null and void. The variables clearly are being assigned data but after the function call it dissapears.

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

I want to get data from a text file and assign it to variables that need to be global. able to be assigned in a function but used outside it. So above is what i was doing to declare them outside the function. because if i declare them inside, i lose scope. It doesnt seem right to declare with 0 and then reassign, but how else can i declare them gloabaly to be manipulated by another function?

next the code is called for the function to do the work

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

The code after GetParams is reporting 0 but inside the function the values are right

The data is read and clearly assigned inside the function. its not pretty or clever but it works.

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 );
         }       
      }       
    }   
})
}

Like i said i know the algorithm is poor, but it works.(Im very noob) but why are the variables not retaining value, and why is the code after GetParams() executed first? Thank you for your time.

Upvotes: 1

Views: 56

Answers (2)

Ridham Tarpara
Ridham Tarpara

Reputation: 6160

fs.readFile asynchronously reads the entire contents of a file. So your console.log('udGasPrice = " + udGasPrice ); won't wait for GetParams function.

Possible resolutions are:

  1. Use callback or promise

    let udGasPrice = 0;
    let udGasLimit = 0;
    let udSlippage = 0;
    
    GetParams(() => {
        console.log("udGasPrice = " + udGasPrice);
    });
    
    function GetParams(callback) {
        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);
                    }
                }
            }
            callback()
        })
    }
    
  2. fs.readFileSync(path[, options]) - it perform same operation in sync - you still need to edit your code accordingly

Also, it's advisable that you don't edit global variables in the function and return updated variables from the function.

Upvotes: 1

Daniel Stoyanoff
Daniel Stoyanoff

Reputation: 1564

The code is executed before the GetParams method finishes, because what it does is an asynchronous work. You can see that by the use of a callback function when the file is being read.

As a best practice, you should either provide a callback to GetParams and call it with the results from the file or use a more modern approach by adopting promises and (optionally) async/await syntax.

Upvotes: 1

Related Questions