Reputation: 11
I have an array of 4 urls and each url has json data. how to loop through urls
ex :
urls =[ "http://url1.com",
"http://url2.com", "http://url3.com", "http://url4.com"];
each url has json one student information like
{ date: 08/05/2014
studentname: 'xyz'
student marks:[
maths:80
science:60
]
}
now i want to loop through all 4 urls in this case 4 students information to get all student marks at once(means some thing like all information into one object]so later i can parse and find out which student has got the highest marks or lowest marks ? how this can be done in node.js ?
Upvotes: 0
Views: 1335
Reputation: 151
This would solve your problem, use the closure property in javascript. Simple, yet efficient. Just have a function which handles the request part and call that function in the loop. And, leave the rest on the lexical scope of functions and closure property.
const request = require("request");
function getTheUrl(data) {
var options = {
url: "https://jsonplaceholder.typicode.com/posts/" + data
}
return options
}
function consoleTheResult(url) {
request(url, function (err, res, body) {
console.log(url);
});
}
for (var i = 0; i < 10; i++) {
consoleTheResult(getTheUrl(i))
}
Upvotes: 1
Reputation: 22508
https://github.com/mikeal/request https://github.com/caolan/async#map
var async = require('async');
var request = require('request');
async.map(urls, function(url, callback) {
request(url, function(err, response, body) {
callback(err, body);
})
}, function(err, students){
if(err) {
return console.error(err);
}
//Do sth. with students array
});
Upvotes: 1