Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何改进nodejs中的代码?_Javascript_Node.js_Express_Mongoose_Mean Stack - Fatal编程技术网

Javascript 如何改进nodejs中的代码?

Javascript 如何改进nodejs中的代码?,javascript,node.js,express,mongoose,mean-stack,Javascript,Node.js,Express,Mongoose,Mean Stack,我在MEAN STACK应用程序中工作,我想改进下面的代码 app.js var express = require("express"); var router = express.Router(); var Comments = require('../models/Comments'); var Posts = require('../models/Posts'); //use in strict mode 'use strict'; //get user comments and p

我在MEAN STACK应用程序中工作,我想改进下面的代码

app.js

var express = require("express");
var router = express.Router();
var Comments = require('../models/Comments');
var Posts = require('../models/Posts');

//use in strict mode
'use strict';

//get user comments and posts
router
    .route("/api/user/getUserCommentsAndPosts")
    .get(
        function(req, res) {

            /*define variable to run sendResponse() function after completed both comment and post query*/
            var commentProcess = 0; //comment process not completed
            var postProcess = 0;   //post process not completed

            /*for store comments and post data in this variable for use in sendResponse() function*/
            var commentGlobal;
            var postGlobal;


            Comments.find({ user_id: req.payload.id }, function(err, CommentsData) {
                if (err) {
                    res.json({ status: 0, code: 200, type: "error", message: err });
                } else {

                    commentProcess = 1; //comment process is completed
                    commentGlobal = CommentsData; //assign local object to global object
                    sendResponse(); // call this function for send api response
                }
            });


            Posts.find({ user_id: req.payload.id }, function(err, PostsData) {
                if (err) {
                    res.json({ status: 0, code: 200, type: "error", message: err });
                } else {

                    postProcess = 1; //post process not completed
                    postGlobal = PostsData; //assign local object to global object
                    sendResponse(); // call this function for send api response
                }
            });

            //run this function after every process
            var sendResponse = function() {
                // check for all process is completed  if completed then send api response
                if (commentProcess !== 0 && postProcess !== 0) {
                    var data ={comments : commentGlobal, posts : postGlobal};
                    res.json({ status: 1, code: 200, type: "success", data: data });
                }
            };

        });
我不想一步一步地在评论和帖子中进行查询,因此我不能说最后将完成哪个过程

如上所述,我认为,我必须制作这种类型的代码

任何机构都可以给我一个改进代码的指导方针吗


谢谢。

您需要某种异步控制库。正如@binariedMe所述,您可以使用
bluebird
,这是一个基于承诺的库,也可以使用
async
,这是一组不同的控制流方法,具有集中的错误处理。

这里是一些重构,当上一次执行的结果传递到下一次执行时

var express = require("express");
var router = express.Router();
var Comments = require('../models/Comments');
var async = require('async');
var Posts = require('../models/Posts');

//use in strict mode
'use strict';

//get user comments and posts
router
    .route("/api/user/getUserCommentsAndPosts")
    .get(function(req, res) {

    async.waterfall([
        function(callback) {

            Comments.find({ user_id: req.payload.id }, function(err, CommentsData) {
                if (err) {
                    callback(err);
                } else {

                    var commentProcess = 1; //comment process is completed
                    var commentGlobal = CommentsData; //assign local object to global object

                    callback(null, commentProcess, commentGlobal);
                }
            });


        },
        function(commentProcess, commentGlobal, callback) {
            Posts.find({ user_id: req.payload.id }, function(err, PostsData) {
                if (err) {
                    callback(err);
                } else {

                    var postProcess = 1; //post process not completed
                    var postGlobal = PostsData; //assign local object to global object

                    callback(null, commentProcess, commentGlobal, postProcess, postGlobal);

                }
            });
        }
    ], function (err, commentProcess, commentGlobal, postProcess, postGlobal) {
        if (err) {
            res.json({ status: 0, code: 200, type: "error", message: err });
        } else {
            var data ={comments : commentGlobal, posts : postGlobal};
            res.json({ status: 1, code: 200, type: "success", data: data });
        }
    });


});
如果您只有很少(2或3)个异步操作,那么您可以使用承诺链操作系统,当第一个调用成功时,另一个将启动

如果您有两个以上的异步操作,或者作为更好的实践,您可以使用异步库。 如果所有异步操作都是独立的,则用户async.parallel。 如果您希望它们以特定的顺序执行,那么请使用user async.瀑布


请检查:

这是我的代码版本。它使用承诺,因此我们可以提出平行请求以获得帖子和评论

const express = require("express");
const router = express.Router();
const Comments = require('../models/Comments');
const Posts = require('../models/Posts');

//use in strict mode
'use strict';

//get user comments and posts
router
  .route("/api/user/getUserCommentsAndPosts")
  .get(
    function (req, res) {
      const userId = req.payload.id; // use const is better than var

      // Do parallel requests using promise.all, it speed up your app indeed
      Promise.all([
        findCommentsByUserId(userId),
        findPostsByUserId(userId)
      ]).then((comments, posts) => {        
        res.json({
          status: 1,
          code: 200,
          type: "success",
          data: { comments, posts }
        });
      })
      .catch(err => {
        res.json({
          status: 0,
          code: 200,
          type: "error",
          message: err
        });
      });      
    });

/**
 * Find comments by user Id
 * - We make this function as promise so we later can do parallel request
 * - We move it to function to make your code in router cleaner and easier to read
 * @param userId 
 */
function findCommentsByUserId(userId) {
  return new Promise((resolve, reject) => {  
    Comments.find({
      user_id: userId
    }, function (err, CommentsData) {
      if (err) {
        reject(err);
      }        

      resolve(CommentsData);      
    });
  });
}

/**
 * Find posts by user Id
 * We make this function as promise so we can later can do parallel request
 * @param userId 
 */
function findPostsByUserId(userId) {
  return new Promise((resolve, reject) => {  
    Posts.find({
      user_id: userId
    }, function (err, PostsData) {
      if (err) {
        reject(err);
      }        

      resolve(PostsData);      
    });
  });
}

希望它有帮助

您需要这样的东西:BinarieMet是正确的。你应该为此做出承诺。有几种不同的promise API。这个问题可能更适合该站点。