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