javascript - 为什么这些变量不能保持价值?
问题描述
我有两个问题我无法弄清楚。当我首先调用 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() 之后的代码首先执行?感谢您的时间。
解决方案
代码在 GetParams 方法完成之前执行,因为它所做的是异步工作。您可以通过在读取文件时使用回调函数来看到这一点。
作为最佳实践,您应该向 GetParams 提供回调并使用文件中的结果调用它,或者通过采用 Promise 和(可选)async/await 语法来使用更现代的方法。
推荐阅读
- python - 可以在python中使用循环保存语法吗?
- kubernetes - Kubernetes 使用 DNS 而不是 IP 创建端点
- javascript - 得到文件的错误错误拒绝承诺试图修复它但它不工作
- css - 材料表角垫清单
- swift - 如何使用 Xcode 11 在 Swift 中实现这一点?
- c++ - cvtColor 忽略 dstCn 参数 OpenCV
- r - 如何更改 geom_miss_point 中缺失值的颜色(使用两种不同的色标)
- vue.js - Vuetify V-Data-Table 页脚添加按钮
- kubernetes-helm - helm中目录的嵌套范围
- python - 训练 1k 图像需要多少个 epoch