async.each(
driver,
function(apiRequest, cb) {
apicall(apiRequest, cb);
},
function(err) {
console.log("error...");
}
);
function apicall(item, cb) {
request(
'https://api.mlab.com/api/1/databases/db/collections/doc?q={"driverid": "' + item + '"}&apiKey=....',
function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log("----->" + body);
var o = JSON.parse(body);
for (var i = 0; i < o.length; i++) {
name[a] = o[i].first_name.concat(" ").concat(o[i].last_name);
modelname[a] = o[i].vehicleused.modelname;
modeltype[a] = o[i].vehicleused.modeltype;
ridescompleted[a] = o[i].ratings.ridescompleted;
avgrating[a] = o[i].ratings.avgrating;
ridescancelled[a] = o[i].ratings.ridescancelled;
behaviour[a] = o[i].ratings.behaviour;
timelypickupdrop[a] = o[i].ratings.timelypickupdrop;
conditionofvehicle[a] = o[i].ratings.conditionofvehicle;
console.log("DRIVER DETAILS---------------------------");
a++;
}
} else
console.log("error....");
}
);
}
Now once I have gathered data in all the 9 arrays, I need to do processing on it. But that can be done only when all the 9 arrays have filled up with data about drivers.
But I am not sure from where to call the process_arrays function() which processes all the arrays only after the async.each has been finished.
The 3rd argument (2nd function) to async.each()
isn't just for errors. It's for specifying any continuation once the iteration has completed (or failed), such as calling process_arrays()
.
async.each(
driver,
function(apiRequest, cb) {
apicall(apiRequest, cb);
},
function(err) {
if (err) console.log("error...", err);
else process_arrays();
}
);
Though, you'll also need to call the cb
within your iterator function, apicall(...)
, for both success and failure. Without doing that, async.each()
won't continue to the next value in the collection.
function apicall(item, cb) {
request(
'https://...',
function(error, response, body) {
if (error || response.statusCode !== 200) {
// argument means failure
cb(error || new Error(response.statusCode));
} else {
console.log("----->" + body);
var o = JSON.parse(body);
// for loop ...
// no argument means success
cb();
}
}
);
}