Your first issue is that your request
call is asynchronous and hasn't yet returned by the time contacts[i].social = results
is executed, so contacts[i].results
is getting assigned an empty array, []. (Variations of this issue are posted on SO multiple times every day, a good explanation of the problem can be found here: How do I return the response from an asynchronous call?) The solution to this is not as simple as just moving contacts[i].social = results;
into inside the request
call success handler because the value of i
will have changed before the handler is called.
Your second issue is that results
is defined outside of the socialScrape
function definition - so instead of having an array of items per request
call, you have one array with all request
results. The best way to resolve your scoping issues is with a closure, which we can achieve by removing the call to socialScrape(homepage);
and making socialScrape
a self-invoking function:
(function socialScrape(homepage) {
var results = [];
var index = i;
request(homepage, function(err, resp, html) {
/* do error and status check stuff and build our results array */
contacts[index].social = results;
});
}(homepage));
Notice how we capture the current value of i
within the closure and assign it to index
. This will allow us to get the correct contact by index when our result is delivered.