【问题标题】:NodeJS Async : Not able to understand the flowNodeJS Async:无法理解流程
【发布时间】:2018-03-22 10:46:28
【问题描述】:
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 完成后处理所有数组。

【问题讨论】:

  • 您为您的 apicall() 函数定义了一个名为 cb 的回调,但您从未真正调用它。因此,apicall() 在完成或出现错误时不会通知任何人。那永远行不通。当异步操作完成或出现错误时,您必须调用回调。
  • 现代的方法是使用 request-promise 库而不是 request,然后使用 Promise 来监视异步操作的完成,而不是 async 库。
  • 谢谢@jfriend00

标签: node.js mongodb asynchronous mlab node-async


【解决方案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();
    }
);

不过,您还需要在迭代器函数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();
            }
        }
    );
}

【讨论】:

  • 是的,它奏效了。谢谢你的详细解释
猜你喜欢
  • 2018-10-13
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多