异步的NodeJS与递推

异步的NodeJS与递推

本文介绍了异步的NodeJS与递推的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经广泛搜索并不能找到,似乎工作答案。我曾尝试Q.deferred,async.series,async.each,我似乎无法得到这个吸盘的工作:

下面是code,这个工作,但是,对于递归前的树出口回归树大火已完成。我已经验证了递归适当挖掘。我真的需要recuriveChildren回报要等到递归调用完成。

\r
\r

exports.tree =功能(REQ,RES){\r
VAR树= {\r
'名':'新帐户\r
};\r
\r
变种方法= {};\r
\r
methods.recursiveChildren =功能(路径){\r
VAR树= {\r
'名':path.field.label +:+ path.match +:+ path.value,\r
'ID':path._id,\r
父:path.parent,\r
孩子们:[]\r
}\r
\r
Path.find({父:path._id})排序({DATE_CREATED:1})。EXEC(函数(ERR,childpaths){\r
\r
对(在childpaths变种Z){\r
VAR tmpTree = methods.recursiveChildren(c​​hildpaths [Z]);\r
subTree.children.push(tmpTree);\r
}\r
\r
});\r
\r
返回子树;\r
\r
}\r
\r
\r
Path.find({父:空})排序({DATE_CREATED:1})。EXEC(函数(ERR,路径){\r
tree.children = [];\r
对(在路径变种X){\r
\r
变种tmpTree = methods.recursiveChildren(路径[X]);\r
tree.children.push(tmpTree);\r
}\r
\r
res.jsonp(树);\r
});\r
 \r
};

\r

\r
\r


解决方案

有关异步模式的困惑的事情是,你不能返回的实际值,因为这还没有发生。你可以在一个函数传递给被执行一次异步操作已完成(回调),或一旦操作解决了一个价值的承诺,您可以返回接受回调(承诺)的对象,将执行回调。

\r
\r

exports.tree =功能(REQ,RES){\r
  VAR树= {\r
    '名':'新帐户\r
  };\r
\r
  变种方法= {};\r
\r
  methods.recursiveChildren =功能(路径){\r
    VAR树= {\r
      '名':path.field.label +:+ path.match +:+ path.value,\r
      'ID':path._id,\r
      父:path.parent,\r
      孩子们:[]\r
    }\r
\r
    返回新希望(函数(解析,拒绝){\r
      Path.find({\r
        父:path._id\r
      })。分类({\r
        DATE_CREATED:1\r
      })。EXEC(函数(ERR,childpaths){\r
\r
        诺言\r
          。所有(childpaths.map(功能(childpath){\r
            / *收集每个子路径的承诺这将返回一个承诺* /\r
            返回methods.recursiveChildren(c​​hildpath);\r
          }))\r
          。然后(功能(resolvedPaths){\r
            subtree.children = resolvedPaths;\r
          \r
             / *顶层承诺得到满足与子树* /\r
            解决(子树);\r
          });\r
      });\r
    });\r
  }\r
\r
\r
  Path.find({\r
    父:空\r
  })。分类({\r
    DATE_CREATED:1\r
  })。EXEC(函数(ERR,路径){\r
    Promise.all(paths.map(功能(路径){\r
      返回methods.recursiveChildren(路径);\r
    }))。然后(功能(resolvedPaths){\r
      tree.paths = resolvedPaths;\r
      res.jsonp(树);\r
    });\r
  });\r
\r
};

\r

\r
\r

I have searched extensively and can not find an answer that seems to work. I have tried Q.deferred, async.series, async.each, I can not seem to get this sucker to work:

Here is the code, this works, however, the "return subTree" fires for the "tree" export before the recursive is complete. I have validated that the recursive is digging appropriately. I really need the return on recuriveChildren to wait until the recursion call is complete.

exports.tree = function(req, res) {
	var tree = {
		'name': 'New Account'
	};

	var methods = {};

	methods.recursiveChildren = function(path) {
		var subTree = {
			'name': path.field.label+":"+path.match+":"+path.value,
			'id': path._id,
			'parent': path.parent,
			'children': []
		}

		Path.find({parent:path._id}).sort({date_created:1}).exec(function (err,childpaths) {

			for ( var z in childpaths ) {
				var tmpTree = methods.recursiveChildren(childpaths[z]);
				subTree.children.push(tmpTree);
			}

		});

		return subTree;

	}


	Path.find({parent:null}).sort({date_created:1}).exec(function (err,paths) {
		tree.children = [];
		for ( var x in paths ) {

			var tmpTree = methods.recursiveChildren(paths[x]);
			tree.children.push(tmpTree);
		}

		res.jsonp(tree);
	});

};

解决方案

The confusing thing about asynchronous patterns is that you can't return an actual value, because that hasn't happened yet. You can pass in a function to be executed once the asynchronous operation has completed (callback), or you can return an object that accepts a callback (a promise), that will execute the callback once the operation resolves the promise with a value.

exports.tree = function(req, res) {
  var tree = {
    'name': 'New Account'
  };

  var methods = {};

  methods.recursiveChildren = function(path) {
    var subTree = {
      'name': path.field.label + ":" + path.match + ":" + path.value,
      'id': path._id,
      'parent': path.parent,
      'children': []
    }

    return new Promise(function(resolve, reject) {
      Path.find({
        parent: path._id
      }).sort({
        date_created: 1
      }).exec(function(err, childpaths) {

        Promise
          .all(childpaths.map(function(childpath) {
            /* collect a promise for each child path this returns a promise */
            return methods.recursiveChildren(childpath);
          }))
          .then(function(resolvedPaths) {
            subtree.children = resolvedPaths;

             /* the top level promise is fulfilled with the subtree */
            resolve(subTree);
          });
      });
    });
  }


  Path.find({
    parent: null
  }).sort({
    date_created: 1
  }).exec(function(err, paths) {
    Promise.all(paths.map(function(path) {
      return methods.recursiveChildren(path);
    })).then(function(resolvedPaths) {
      tree.paths = resolvedPaths;
      res.jsonp(tree);
    });
  });

};

这篇关于异步的NodeJS与递推的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 23:19