I am making a small application using eel, and part of the application's functionality requires it to read data from a text file and store it as a variable within javascript. The issue I am having is, when I try to assign the text to a variable, the variable becomes empty once leaving the scope of the eel call.
Here is an example:
main.py
@eel.expose
def ReturnTextString(train):
# Create the data file path using the train param
file = "data/{}.txt".format(train)
# Store data to string
dataFile = open(file, "r")
moduleInfo = dataFile.read()
dataFile.close()
return moduleInfo
script.js
// Initialize the variable that will hold the data being read
var newData = "";
// Function that will assign what has been returned from python to our variable "newData"
async function assign(){
newData = await eel.ReturnTextString("ps1")();
console.log(newData); // <--- This console.log correctly prints the data from the text document
}
// Literally just print newData
function printCorrectly(){
console.log(newData); // <--- This console.log prints an empty line
}
// Ideally, this call would assign our text to "newData"
assign();
// And then this would confirm that it survived leaving the scope of assign()
printCorrectly();
// But it does not :(
It seems like a scope issue, but what throws me for a loop is the fact that "newData" is a global variable, and it appears to lose its value when the program exits the scope of the assign function. I am also fairly new to eel as this is my first time working with it. If someone could explain what's going on and any potential solutions that would be amazing, thanks!
CodePudding user response:
assign()
would change the global variable newData to 'data from the text document' but by the time printCorrectly()
is called the promised has not yet been resolved because of the timeout and even if you resolve the promise immediately it will still only change it after the printCorrectly()
has run because the promise will be queued as a Microtask.
You can simply wait for assign() to complete first and then printing the data like this:
assign().then(() => printCorrectly())
or you add a setTimeout to wait for the assignment or a setInterval to check for when it happens (Not recommended though).
setTimeout(() => printCorrectly(), 0);
or setTimeout(() => printCorrectly(), 1000);