I have to implement a logic like this:
var express = require('express'),
request = require('request');
var array = [
{ url: 'http://www.example1.com' },
{ url: 'http://www.example2.com' },
];
express.Router().get('/job', function (req, res) {
results = [];
array.forEach(function (item) {
request(item.url, function (error, response, body) {
if (!error && response.statusCode == 200) {
results.push(body);
}
});
res.json(results); // <== wrong, results array is empty, here...
});
How do I call res.json(results) being sure forEach loop is ended?
UPDATE: it is not a duplicate of suggested answer!
I need to res.json() when all requests are completed, and not when forEach loop is finished... :-(