我在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 });
}
};
});
我不想在评论中进行查询并逐步发布,因此我不能说最后会完成哪个过程。
如上所述,我必须制作这种类型的代码。
任何机构都可以为我提供改进此代码的指南。
感谢。
答案 0 :(得分:1)
如果你有少量(2或3)异步操作,那么你可以使用promise chaining os,当第一次调用成功时,另一次启动。
如果您有两个以上的异步操作或更好的做法,您可以使用异步库。 如果所有异步操作都是独立的,那么用户async.parallel。 如果您希望它们按特定顺序执行,请使用async.waterfall
答案 1 :(得分:0)
您需要某种异步控制库。正如@binariedMe所述,您可以使用bluebird
这是一个基于承诺的库,或者您可以使用async
这是一组具有集中错误处理的不同控制流方法。
答案 2 :(得分:0)
以前执行的结果传递给下一个
时,会对async waterfall进行一些重构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 });
}
});
});
答案 3 :(得分:0)
这是我的代码版本。它使用promise,因此我们可以并行请求以获取帖子和评论。
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);
});
});
}
希望有帮助