I think I am using asynchronous functions in a completely wrong way, and need some help.
I want my function to:
Scan an array of objects
Test the "Name" value of each object against a regular function; make a http request (ie, "www.foobar.com/"+array.Name) using request, returns 1 if source does exist.
If both these conditions are true, add object to a new array
When array is fully scanned, save the new array into a file
It all works; however, the asynchronous calls finish running AFTER the file is written!
Example:
function checkName(foo) {
request("www.foobar.com/"+foo, function(error, response, body) {
if (!error && response.statusCode == 200)
return 1;
else
return 0;
});
}
function checkSrc(foo) {
for (var i = 0; i < 10; i++) {
if (!(banlist.test(foo[i].name)) && checkName(foo[i].name)) {
str.push(foo[i]);
}
count++;
}
}
Here begins the actual execution: I read the source file, want to populate 'data' with the array created by 'checkSrc', then save it to a file.
As I said above the requests finish after the file is saved, thus I have an empty array in the final object.
fs.readFile('./data.js', function read(err, data) {
if (!err) {
console.log("Response received!");
var dump = JSON.parse(data);
var len = dump.applist.apps.length;
var str = [];
console.log("Parsing...");
checkSrc(dump.list);
var final = {
"list": str
};
str_final = JSON.stringify(final);
fs.writeFile("parsed.js", str_final, function(err) {
if (err) {
return console.log(err);
}
});
};
});
I have found some similiar questions here in stackoverflow, but none of them make http requests; I have tried to wrap my cycle into a function, but it did not work either. I have tried using the request-sync and sync-request node modules, but seem to be deprecated.