NodeJS Promises,Recursion,Asynchronous继续

时间:2015-08-18 21:55:31

标签: javascript node.js asynchronous recursion promise

@lyjackal帮助我(NodeJS Asynchronous and Recursive)解决了寻找孩子的递归问题。

我仍然试图了解nodejs的承诺。我和前一篇文章有​​类似的问题,但略有不同。我觉得这段代码很接近,但它不起作用。

我有一个Assignment,Assignment有一个Path的引用。该路径和所有路径可能有也可能没有父路径。我需要这个代码,找到路径的路径,然后在数组中堆叠每个路径的一些属性。最后的数组看起来像这样:

[ [0]=>{field: name, match: match_type, value:value},
  [1]=>{field: name, match: match_type, value:value},
  ...]

阵列的顺序并不重要。这是带有Promises的代码......已经破解了:

exports.assignRecursiveQuery = function(req,res) {
    var methods = {}
    var query_to_save = []

    methods.recursiveParents = function(path) {
        return new Promise(function(resolve, reject) {
          Path.find({
            _id: path.parent
          }).exec(function(err, parentPaths) {
            Promise
              .all(parentPaths.map(function(parentPath) {
                return methods.recursiveParents(parentPath) 
              }))
              .then(function(promisedPaths) {
                return resolve(promisedPaths);
              });
          });
        });
      }

    Path.find({_id: req.assignment.path_end}).exec(function(err,lastPaths) {
        //add first query rule
        console.log(lastPaths[0]);
        query_to_save.push({field:lastPaths[0].field.api,match:lastPaths[0].match,value:lastPaths[0].value})

        Promise.all(lastPaths.map(function(path) {
          return methods.recursiveParents(path);
        })).then(function(resolvedPaths) {
            for( var x=0; x<resolvedPaths.length; x++ ) {
                console.log(resolvedPaths[x])
                query_to_save.push({field:resolvedPaths[x].field.api,match:resolvedPaths[x].match,value:resolvedPaths[x].value});
            }
            console.log(query_to_save);
            res.jsonp(req.assignment)
        });
    });
}

1 个答案:

答案 0 :(得分:0)

我按照以下代码使用它可以正常工作,不确定它是否是正确的方式&#34;但它确实按预期工作。

&#13;
&#13;
$(function() {

  /** 
  Whenever user types a letter and release the key, its value is passed to the 
  foodQuery function 
  **/
  $("#search").keyup(function() {
    var value = $(this).val();
    foodQuery(value);
  });

  function foodQuery(key) {    // key is passed as a parameter

    var foodURL = "http://api.example.com/items?key=" + key;

    /** Send you ajax request here and manipulate the DOM the same way yo do. Since we are 
    fetching new products continuously, it is better to clear the .listing element 
    every-time before you update it. **/

    $(".listing").html("");

    /** 
    $.ajax({
        url: foodURL,
        type: 'GET',
        contentType: "text/plain",
        dataType: 'json',
        success: function(json) { **/
  }

});
&#13;
&#13;
&#13;