javascript - 如何改进我在 nodejs 中的代码?

标签 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 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 });
                }
            };

        });

我不想在评论里查询,一步步发帖,所以我也不好说最后会完成哪个过程。

如上所述,我必须编写此类代码。

任何人都可以给我一个改进此代码的指南。

谢谢。

最佳答案

如果您有很少(2 或 3)个异步操作,那么您可以使用 promise chaining os,当第一次调用成功时另一个开始。

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

请检查:https://github.com/caolan/async

关于javascript - 如何改进我在 nodejs 中的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37990882/

相关文章:

javascript - 如何根据 JSON 文件中的 bool 值自动更改 img

javascript - Angular JS 教程 - 需要澄清

javascript - Express 不使用 Fetch API 通过 POST 从 React 接收参数

mysql - 连接失败 : Error: connect ETIMEDOUT

node.js - 如何在 Express 路由中设置 Next.js 渲染?

javascript - 为什么 google cloud vision Logo detection 在同一张图片上返回不同的结果?

javascript - 如何将 php 中接收到的数据分类为 html 中的 3 个不同的 div 标签?

javascript - 如何打印 DOM 对象的选择器

node.js - Openshift3 构建意外失败

javascript - 来自http请求的Node.js响应不调用 'end'事件而不包括 'data'事件