Node js async fs.fileRead variable parsing [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I have the whole code wrapped by an async function, i'm using puppeteer basically.
If i use a simple fs.fileRead function, save the result of data inside a var then the code can read that variable in the next async function, and from my understanding it can read it exactly because is async same as the fs.fileRead function.
The problem comes when I try to do another fs.fileRead, way before the above, but in the same tree level, and try to read the variable saved inside it, in a if (){ statement right after, outside the fs.fileRead, I tried using a function but doesn't work either, below the example:
var fullcsv, filecsv;
fs.readFile('myfile.csv', (err, data) => {
if (err) {throw err;}
fullcsv = data.toString();
if(fullcsv.includes(urldom)){
filecsv = 0;
}else{
filecsv = 1;
}
processFile(filecsv);
});
var dog;
function processFile(filecsv) {
dog= filecsv;
}
console.log(dog);
if (urllink != "" && processFile() == 1){
...
The console says console.log(dog) is undefined , and the if statement turns out to be false cause it goes directlye to the else statement.
p.s. I also tried with fs.fileReadSync but does literally no difference at all.

Related

JQuery Getting value undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I have the following JQuery script:
var loaded_data = {};
function data_load(callback) {
$.getJSON('get_data.php', function (data) {
$.each(data, function (fieldName, fieldValue) {
loaded_data[fieldName] = fieldValue;
});
});
callback();
}
function add_data() {
alert(loaded_data["courses"]);
}
data_load(function () {
add_data();
});
The function data_load() working properly and loading data. But when I am trying to call add_data() function, I am getting Undefined in alert message.
If I am Typing loaded_data["courses"] on console on browser, I am getting desired output.
I don't know loaded_data["courses"] is working properly on Browser console but not on script.
Is There anything like alert() is executing before loading data from get_data.php?

Javascript scope variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
var preGameRequest = new XMLHttpRequest();
var preGameData;
preGameRequest.open("GET", "/matches/live.json");
preGameRequest.onload = function() {
preGameData = JSON.parse(preGameRequest.responseText);
}
preGameRequest.send();
console.log(preGameData); // main problem is here
Here is my code. I defined preGameData as global and tried to save /matches/live.json file's data into preGameData. And when I try to console.log(preGameData) from outside of the scope (like in the code section) I get 'undefined' as a return. And if I try to console.log(preGameData) from inside of the scope it works. I don't really know what's going on.
That code should work:
preGameRequest.onload = function() {
preGameData = JSON.parse(preGameRequest.responseText);
console.log(preGameData);
}
The reason: is that preGameRequest.send() function operates asynchronous.
When the browser tries to execute console.log() (in your example), the http response is not recieved yet, and the variable is really undefined.
But if you place console.log() inside of the handler (as in my example), it would be executed at moment, when the response is already recieved (straight in the onload() handler). And that's why the variable preGameData would be defined already.

Access to a variable, which is output from an async function [duplicate]

This question already has answers here:
Saving data from the d3.js ajaxrequest in a variable to create axis with data
(2 answers)
Closed 7 years ago.
I have a problem with this snippet:
d3.csv("data/airports.csv", function(err, a) {
var count=0;
a.forEach(function(i){
if(i.iata_faa == ""){}
else {
count++;
addpoint(i.lon, i.lat,i);
}
});
airports=a;
myDataIsReady();
console.log(count);
});
function myDataIsReady(){
console.log(airports);
return airports;
}
console.log(airports);
Notice that airports is a global variable here.
I need to handle the variable airports for another function, but the value is null, I think that is null because the csv file has not yet been processed completely, right?
How I resolve it?
Generally for async functions, you push a callback (a function reference) into the async method, so that it processes the data when the ajax call completes. You don't return data from that type function, you inject data into it.

Use child_process.exec's return value in if statements? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I have this function:
function checkfType(a,b){
exec("file '"+a+"'",function(err,stdout,stderr){
if(stdout.containsString(b)===true){return true}else{return false}
})
}
However, if I use it in an if statement like this:
if(checkfType(".","directory"){}, it just goes "false".
I tested the exec function as a non-function and using it instead of the if statement:
exec("file '.'",function(err,stdout,stderr){
if(stdout.containsString("directory")===true){
console.log("It works!);
}else{
console.log("It doesn't work.";}
});
Which works just fine.
I am led to believe tha the exec function is async (or similar), which is where my problem lies.
Is there any way to use exec's output in an if statement?
Is there any way to use exec's output in an if statement?
Yes, but not as a return value for the function calling it.
I am led to believe that the exec function is async (or similar), which is where my problem lies.
Right. Your function will need to accept a callback that it will pass the flag to when the exec completes:
function checkfType(a,b,callback){
exec("file '"+a+"'",function(err,stdout,stderr){
callback(stdout.containsString("directory"));
})
}
Usage:
checkfType("whatever", "directory", function(flag) {
if (flag) {
// It's a directory
} else {
// It isn't
}
});

javascript variable scope issue undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
function getData() {
var photo,
comment,
url;
$.getJSON('http://url.info/verify/settings.php', function (data) {
photo = data.photoMSG;
comment = data.commentMSG;
url = data.photoURL
});
console.log(photo); //undefined
console.log(comment); //undefined
console.log(url); //undefined
}
I'm getting undefined in console log for all of them... How to get these 3 vars visible outside of getJOSN block? I know this have been asked x100 times, I tried windiw.varName but still the same thing..
It's not a scope issue, it's an asynchronous issue. Everything inside the getJSON handler is asynchronous -- so the console.log calls will usually happen after the variables get assigned. Use an async callback instead:
$.getJSON('http://url.info/verify/settings.php', function (data) {
photo = data.photoMSG;
comment = data.commentMSG;
url = data.photoURL;
callback(photo, comment, url);
});
function(photo, comment, url) {
console.log(photo); //undefined
console.log(comment); //undefined
console.log(url); //undefined
}
Because $.getJSON is doing an ajax call, but the code after that is called before the callback within the getJSON is called. So the vars are still undefined. A typical "problem" with asynchronous behaviors.

Categories

Resources