如何使节点js api同步以解雇mongodb的多个查询?

时间:2017-09-11 06:59:21

标签: node.js

我在node.js中有一个api,它通过名称查找类别的id,当结果出现时,它会在另一个函数中发送此id并调用其所有父类别id。如果没有任何父类别,那么在数组中它应该被添加,如果有父类,那么它也应该在数组中添加。我的问题是响应是因为异步调用而发送一个空数组。如何通过async-waterfall进行同步?请帮助我。谢谢你提前

    router.post('/api/getproductofcategory', function(req, res) {
      var name = req.body.category;
      var cidarray = [];

      Category.getCategoryIdByname(name, function(err, categoryId) {
        if (err) {
          throw err;
        }

        if (categoryId.length) {
          console.log(categoryId);
          Category.getcategoryWithSameParentFun(categoryId[0]._id, function(
            err,
            categoryWithSameParent
          ) {
            if (err) {
              throw err;
            } else {
              console.log(categoryWithSameParent);
              if (categoryWithSameParent.length == 0) {
                cidarray.push(categoryId[0]._id);
              } else {
                cidarray.push(categoryWithSameParent._id);
              }

Product.getProductByCategoryid(cidarray[0], function(err, products){
                if(err){
                    console.log('error', err);
                }
                else{
                    console.log(products);
                            } 

            })
}
          });
        }
      });

      res.end('result', cidarray);
    });

1 个答案:

答案 0 :(得分:0)

我稍微改变了变量名并做了一些评论。我不知道您为什么要将cidarray作为API响应发送,但无论如何,这就是您基本上使用async/each控制流量的方式。

const each = require('async/each');

router.post('/api/getproductofcategory', function(req, res) {
  var name = req.body.category;
  var cidarray = [];

  Category.getCategoryIdByname(name, function(err, categoryIds) {
    if (err) {
      throw err;
    }

    each(
      categoryIds,
      function(categoryId, callback) {
        Category.getcategoryWithSameParentFun(categoryId._id, function(
          err,
          categoryWithSameParent
        ) {
          if (err) {
            throw err;
          } else {
            if (categoryWithSameParent.length == 0) {
              cidarray.push(categoryId[0]._id);
            } else {
              cidarray.push(categoryWithSameParent._id);
            }
            callback();
          }
        });
      },
      function(err) {
        // Here your cid array is filled with desired values.

        each(
          cidarray,
          function(cid, callback) {
            Product.getProductByCategoryid(cid, function(err, products) {
              if (err) {
                console.log('error', err);
              } else {
                // Don't know exactly what you're trying to do with products here.
                // Whatever it is you should call callback() after you do your job with each cid.
                console.log(products);
              }
            });
          },
          function(err) {
            // Final step. You end your response here.
            res.end('result', cidarray);
          }
        );
      }
    );
  });
});