I'm trying to extract a piece of information as soon as it is available. It could be available first on 4 different websites, so I have created regex expressions for each URL I can find the information and stored these values in an array:
var sources = [{
url: URL1
regex: REGEX1
},
{
url: URL2
regex: REGEX2
}, etc.];
I then loop over these with a for loop and want to test them one at a time for the information. This for loop is set on a 30 second interval, so I want all of the websites to be tested every 30 seconds.
for (var i = 0; i < data.sources.length; i++)
{
var source = data.sources[i];
var url = source.url;
var regex = source.regex;
// this is npm request
request(url, function(error, response, html)
{
//EDIT INCLUDED HERE: HIGH-LEVEL OVERVIEW
->check to see if data has been updated
->if yes, use the capturing regex groups to enter data into MySQL table
}
}
The issue is, because request is a callback function (or 'has' a callback function?), regex and url as overwritten before anything can be done with them. So the request will fire and I will get valid HTML, but then regex is set to a value that isn't valid for that url. I need help coming up with one of two solutions:
- (Preferable): pass the regex to the request function so that it is local to that function and doesn't get over written. This would be great because it would allow all of the requests to in a non-blocking manner.
- Have the request functions wait until the previous one is finished before continuing through the for loop.