异步node.js数据流混乱 [英] Async node.js data flow confusion

查看:73
本文介绍了异步node.js数据流混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的帮助...在如何正确处理此问题上花费了大量时间.我现在处于异步状态,放弃了正确编写回调的能力.我有一段代码,我在其中传递一组随机数(每个记录),并将它们传递给猫鼬调用.尝试根据我通过的多个查询创建数据集.

thanks for your help...struggling big time with how to handle this properly. I'm in async now, having given up on my ability to write the callbacks properly. I have snippet where I'm passing a set of random numbers (eachrecord) and passing them through to a mongoose call. Trying to create a data set from the multiple queries I pass.

我的问题是,无论我做什么4个小时,"newarray"变量始终为空.

My issue is that no matter what I've done for 4 hours, the "newarray" variable is always empty.

谢谢您的帮助-

async.forEach(arLimit, function(eachrecord, callback){

  newarray = new Array;

  var query = UGC_DB_Model.find({}).skip(eachrecord).limit(-1);

  query.execFind(function (err, data) {
    if (err)
      console.log(err);
    else {
      newarray.push(data);
    }
  });

   callback(null, newarray);

}, function(err, result) {
  if (err) return next(err);
      console.log("(it's empty): " + result); 
}); 

推荐答案

您的代码有几个问题:

  • async.forEach 并非旨在生成"结果, async.map 是什么;
  • 仅当完成execFind时才需要调用回调,而不是在调用后立即调用;
  • 您的newarray可能不是必需的;
  • async.forEach isn't meant to 'generate' results, that's what async.map is for;
  • you need to call the callback only when execFind is done, and not immediately after calling it;
  • your newarray is probably not necessary;

因此,请尝试以下操作:

So try this instead:

async.map(arLimit, function(eachrecord, callback){

  var query = UGC_DB_Model.find({}).skip(eachrecord).limit(-1);

  query.execFind(function (err, data) {
    if (err)
      callback(err); // pass error along
    else {
      callback(null, [ data ]);
      // although I think you mean this (because 'data' is probably an array already)
      //   callback(null, data);
    }
  });

}, function(err, result) {
  if (err) return next(err);
  console.log("(it's empty): " + result); 
}); 

这篇关于异步node.js数据流混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆