I have the following Java Script code fragment:
function upoload_TC(evt) {
var file = evt.target.files[0];
if(file.type != 'text/plain'){
evt.target.style='color:red;';
}
else{
var app_data='';
reader = new FileReader();
reader.onload = function(){
app_data = reader.result;
};
reader.readAsText(file);
if (evt.target.id[7]=='2') {
/* area of intrest begin: */
var packet_order = get_packet_order(evt.target);
console.log("1st");
var app_data1 = app_data.split('\n');
console.log("app_data: ");
console.log(app_data);
console.log("app_data1: ");
console.log(app_data1);
/* area of intrest end */
for(var i=0; i<app_data1.length; ++i){
console.log("3st");
if(app_data1[i][0] == '!'){
app_data1.splice(i,1);
--i;
console.log(app_data1);
}
console.log(app_data);
...
}
}
}
}
app_data
have a long string.
After execution, sometimes app_data1
do not have any content logged.
Observation: When I execute it step by step in the debugger, app_data1
has the expected value. But if my 1st break point is after the assignment statement for app_data1
, it's empty.
How can I fix this?
I found a call_back
and promises
to tackle this kind issues for user-defined functions. Since split()
is not defined by me, I think these won't work.
I believe timeout
is not the correct way to do this. Is it?
Please find the video of debugger window here.
You should be doing the logging / processing inside the onload
callback. In your example code, you're setting the value for app_data
on the load
event, which is fired after the asynchronous function readAsText
finishes its thing. By that time the logging / processing code has already been executed.