Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将数据推送到外部异步函数_Javascript_Arrays_Node.js_Asynchronous - Fatal编程技术网

Javascript 将数据推送到外部异步函数

Javascript 将数据推送到外部异步函数,javascript,arrays,node.js,asynchronous,Javascript,Arrays,Node.js,Asynchronous,我仍然不能很好地处理异步函数,我有一个项目数组,我试图为每个项目计算一些值,并推送到异步函数之外的另一个数组。然后我想做一些统计计算并发送到前端。这是服务器端,nodejs处理程序,我的代码: exports.register = function (plugin, options, next) { function isInArray(value, array) { return array.indexOf(value) > -1; } function stat

我仍然不能很好地处理异步函数,我有一个项目数组,我试图为每个项目计算一些值,并推送到异步函数之外的另一个数组。然后我想做一些统计计算并发送到前端。这是服务器端,nodejs处理程序,我的代码:

exports.register = function (plugin, options, next) {

  function isInArray(value, array) {
    return array.indexOf(value) > -1;
  }

  function statistics(values) {
    var sum = math.sum(values);
    var max = math.max(values);
    var min = math.min(values);
    var stddev = math.std(values);
    var mean = math.mean(values);
    var count = values.length;
  }

  plugin.route({
    method: 'GET',
    path: '/statistics/{orgId}/layout/{layoutId}',
    config: {
      pre: [
        authorize(hasRole(['OPERATIONAL', 'STRATEGIC', 'LOP', 'TACTICAL']))
      ],
      handler: function (request, reply) {

        Category.find()
        .where('organization')
        .equals(request.params.orgId)
        .exec(function (err, categories) {

          var weight = [];
          var price = [];
          var volume = [];
          var thisAR = [];

          if (err || categories === null) {
            return reply(Boom.badRequest('Categoria inexistente'));
          } else {

            Location.findById(request.params.layoutId)
            .exec(function (err, layout) {
              if(err) {
                console.log(err);
              }

              var searchItems = function searchItems(category, next) {

                Item.find()
                .where('category')
                .equals(category._id)
                .exec(function (err, items) {

                  if (err) {
                    console.log(err);
                  } else {
                    var valuesToCalculate = [];
                    var itemsFiltered = [];
                    _.forEach(items, function(item) {
                      if(item.location && item.location !== null) {
                        if(isInArray(item.location.toString(), layout.contents)) {
                          itemsFiltered.push(item);
                        }
                      }
                    });
                    valuesToCalculate.push(itemsFiltered.length * category.data.weight);
                    valuesToCalculate.push(itemsFiltered.length * category.data.price);
                    valuesToCalculate.push(itemsFiltered.length * category.data.volume);
                    next(valuesToCalculate);
                  }
                });
              }

              var onFinish = function onFinish(value, err) {
                if(err) {
                  console.log(err);
                }
                console.log(value);
                thisAR.push.apply(value);
              }

              async.each(categories, searchItems, onFinish);
              console.log(thisAR);
              //var arrays = [statistics(weight), statistics(price), statistics(volume)];
              //return arrays;
            });
          }
        });
      }
    }
  });

  next();
};

关于这件事,我有几件事很突出。首先,只有在出现错误或categories为null时才调用reply。此外,您正在尝试将非空值传递给async.each回调。根据这一点:,“如果没有发生错误,回调应该在没有参数或显式空参数的情况下运行”。我想您可能误解了onFinish回调如何与async.each.一起工作。。它不是为每个项调用的,而是在所有迭代器函数完成后调用的。因此,与其在onFinish中将项目推送到thisAR上,不如在searchItems中这样做。我认为这应该奏效:

exports.register = function (plugin, options, next) {

  function isInArray(value, array) {
    return array.indexOf(value) > -1;
  }

  function statistics(values) {
    var sum = math.sum(values);
    var max = math.max(values);
    var min = math.min(values);
    var stddev = math.std(values);
    var mean = math.mean(values);
    var count = values.length;
  }

  plugin.route({
    method: 'GET',
    path: '/statistics/{orgId}/layout/{layoutId}',
    config: {
      pre: [
        authorize(hasRole(['OPERATIONAL', 'STRATEGIC', 'LOP', 'TACTICAL']))
      ],
      handler: function (request, reply) {

        Category.find()
        .where('organization')
        .equals(request.params.orgId)
        .exec(function (err, categories) {

          var weight = [];
          var price = [];
          var volume = [];
          var thisAR = [];

          if (err || categories === null) {
            return reply(Boom.badRequest('Categoria inexistente'));
          } else {

            Location.findById(request.params.layoutId)
            .exec(function (err, layout) {
              if(err) {
                console.log(err);
              }

              var searchItems = function searchItems(category, next) {

                Item.find()
                .where('category')
                .equals(category._id)
                .exec(function (err, items) {

                  if (err) {
                    console.log(err);
                  } else {
                    var valuesToCalculate = [];
                    var itemsFiltered = [];
                    _.forEach(items, function(item) {
                      if(item.location && item.location !== null) {
                        if(isInArray(item.location.toString(), layout.contents)) {
                          itemsFiltered.push(item);
                        }
                      }
                    });
                    valuesToCalculate.push(itemsFiltered.length * category.data.weight);
                    valuesToCalculate.push(itemsFiltered.length * category.data.price);
                    valuesToCalculate.push(itemsFiltered.length * category.data.volume);
                    thisAR.push.apply(valuesToCalculate);
                  }
                  next(err);
                });
              }

              var onFinish = function onFinish(err) {
                if(err) {
                  console.log(err);
                }
                console.log(thisAR);
                // call reply here
              }

              async.each(categories, searchItems, onFinish);
              console.log(thisAR);
              //var arrays = [statistics(weight), statistics(price), statistics(volume)];
              //return arrays;
            });
          }
        });
      }
    }
  });

  next();
}; 

我不能评论,因为我是新手,但似乎只是删除了
thisAR.push.apply(valuesToCalculate)中的
.apply
将向您的控制台返回完整数组。log。

感谢@MikeAtkins的重播,是的,我完全误解了onFinish函数的功能。我试过你说的,但是onFinish函数中的console.log是空的。我错过了什么?我不确定。旁注:为了更好地处理错误,我将对next的调用从
else
正文中移出,并将err作为参数添加到next中。你们根本看不到任何控制台消息吗?你们也确定这些项不是空的吗?有了@brian baker的评论,这就完美了。谢谢