从async.parallel node.js返回结果到父函数

时间:2018-09-22 19:46:33

标签: node.js asynchronous callback controller

我是node.js的新手,需要帮助。我需要将save()结果发送到控制器,但它是隔离的。我不知道正确执行此操作的方式。应该是回调(试图了解其工作原理)还是其他解决方案。您能解释一下如何针对特定案例进行解决吗?

谢谢。

从控制器调用的方法:



    exports.createProduct = function (req) {

      async.parallel({
        // Search for genre existent id's sent from client
        genres: (callback) => {
          Genre.find({_id: {$in: req.body.genre}}, '_id').exec(callback);
        }
      }, (err, docs) => {
        // if (err) { throw err; }
        // Assign found genres
        req.body.genre = docs.genres;

        let product = new Product({
          title: req.body.title,
          description: req.body.description,
          images: req.body.images,
          genres: req.body.genre,
          price: req.body.price,
          status: req.body.status,
          sold: req.body.sold,
        });
        return product.save();
      });
      // return to Controller
    };

1 个答案:

答案 0 :(得分:0)

You can do it passing a callback function for createProduct function like this

// Product module

exports.createProduct = function (req, callback) {

    async.parallel({
    // Search for genre existent id's sent from client
    genres: (callback) => {
      Genre.find({_id: {$in: req.body.genre}}, '_id').exec(callback);
    }
  }, (err, docs) => {
    // if (err) { throw err; }
    // Assign found genres
    req.body.genre = docs.genres;

    let product = new Product({
      title: req.body.title,
      description: req.body.description,
      images: req.body.images,
      genres: req.body.genre,
      price: req.body.price,
      status: req.body.status,
      sold: req.body.sold,
    });
    product.save();

    return callback(/* You can pass any params here*/);
  });
  // return to Controller
};


/// Controller module


const product = require('./lib/product');

exports.controllerFunction = () => {
    product.createProduct(req, (params) => {
        // Called when product is created
    })
}