async.map完成后执行功能

时间:2018-10-12 06:19:58

标签: javascript node.js callback promise async-await

下面的函数可以在数组 urls_global_query

中发出所有请求
module.exports.data_query_fire_test = function(day_y_n,glt_y_n)
{
    var druid_output_agg = [];
    var urls_global_query=druid.query_builder(day_y_n,glt_y_n);
        async.map(urls_global_query, request, function(err, results_chart) {
          if (err) 
            {
              throw (err);
            }
          for (var i = 0; i < results_chart.length; i++) 
          {
              for (var j = 0; j < results_chart[i].body.length; j++) 
              {
                    druid_output_agg.push(results_chart[i].body[j]["event"]);
              }
          }
                    console.log("length : ",druid_output_agg.length);
                    return druid_output_agg;
        });
    };

当被呼叫

console.log("output : ",druid_exe.data_query_fire_test(0, 0));

什么都不会返回,但

length : 1025

是在控制台上打印的,因此async.map在所有请求完成后不返回值的情况下工作正常。

我的意图是实现这样的同步呼叫

druid_exe.data_query_fire(0,0,function(data){
    console.log(" process 1 : ",data.length);
    druid_exe.data_query_fire(1,0,function(data){
            console.log(" process 2 : ",data.length);
            druid_exe.data_query_fire(1,1,function(data){
                console.log(" process 3 : ",data.length);
            });
    });
});

还尝试创建如下的Promise:

module.exports.data_query_fire_test = function(day_y_n,glt_y_n)
{
    var druid_output_agg = [];
    var urls_global_query=druid.query_builder(day_y_n,glt_y_n);
    Promise.all(
        async.map(urls_global_query, request, function(err, results_chart) {
          if (err) 
            {
              throw (err);
            }
          for (var i = 0; i < results_chart.length; i++) 
          {
              for (var j = 0; j < results_chart[i].body.length; j++) 
              {
                    druid_output_agg.push(results_chart[i].body[j]["event"]);
              }
          }
                        return druid_output_agg;
        })).then(function(results){
            console.log("output length : ",results.length);
        })
    };

但是出现以下错误:

(node:7410) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
    at Function.all (<anonymous>)
    at Object.module.exports.data_query_fire (/Users/srajathii/Desktop/DLV_testinng/copy-node/hikma-new/Site/bin/druid_executors.js:90:13)

0 个答案:

没有答案