NodeJS Async:无法理解流程

NodeJS Async : Not able to understand the flow

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 function(),它仅在 async.each 完成后才处理所有数组。

async.each() 的第三个参数(第二个函数)不仅仅用于错误。它用于在迭代完成(或失败)后指定任何延续,例如调用 process_arrays().

async.each(
    driver,
    function(apiRequest, cb) {
        apicall(apiRequest, cb);
    },
    function(err) {
        if (err) console.log("error...", err);
        else process_arrays();
    }
);

不过,您还需要在迭代器函数 apicall(...) 中调用 cb 以判断成功与否。如果不这样做,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();
            }
        }
    );
}