【发布时间】:2016-10-25 17:51:46
【问题描述】:
我正在使用 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 });
}
};
});
我不想在评论和帖子中一步一步地进行查询,因此我不能说最后会完成哪个过程。
如上所述,我必须制作这种类型的代码。
任何机构都可以给我一个改进此代码的指南吗?
谢谢。
【问题讨论】:
-
你需要这样的东西:npmjs.com/package/bluebird
-
BinariedMe 是正确的。你应该为此使用承诺。有几种不同的 Promise api。
-
这个问题可能更适合Code Review 网站。
标签: javascript node.js express mongoose mean-stack