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....");
}
);
}
现在,当我在所有9个阵列中收集数据后,我需要对其进行处理。但只有当所有9个阵列都填满了有关驱动程序的数据时,才能做到这一点。
但我不确定从哪里调用process_arrays函数(),它只在async.each完成后处理所有数组。
答案 0 :(得分:1)
async.each()
的第三个参数(第二个函数)不仅仅是出错。它在迭代完成(或失败)后指定任何延续,例如调用process_arrays()
。
async.each(
driver,
function(apiRequest, cb) {
apicall(apiRequest, cb);
},
function(err) {
if (err) console.log("error...", err);
else process_arrays();
}
);
但是,您还需要在迭代器函数cb
中调用apicall(...)
,以获取成功和失败。如果不这样做,async.each()
就不会继续收集集合中的下一个值。
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();
}
}
);
}