初学node,很不适应这种异步的编码方式,以下是一个简单的route,获取三份数据,分别是:
- 文章目录
- 首要文章
- 最近文章
其中1,2无关联,随意执行,3是要2加载后,才能加载。 所以我用到3个promise,1,2并一起一个,3一个,整个代码下来,我觉得好丑。 不知道你们怎么写的?
var _ = require("lodash");
var express = require('express');
var router = express.Router();
const helper = require("../lib/helper");
const Category = require("../models/categories");
const Article = require("../models/articles");
const viewHelper = require("../lib/viewHelper");
var cateDb = new Category();
var articleDb = new Article();
var topArticleCount = 2;
function findCates() {
return new Promise(function (resolve, reject) {
cateDb.findAll(function (items) {
console.log("cate count:" + items.length);
resolve(items);
});
});
}
function findArticles() {
return new Promise(function (resolve, reject) {
articleDb.findTop(2, function (results) {
resolve(results);
});
});
}
/**
* 最近文章
*/
function findNewArticles(excludeIDs) {
return new Promise(function (resolve, reject) {
articleDb.find({ size: 3 + topArticleCount, index: 1 }, function (docs) {
_.remove(docs, item => {
return excludeIDs.includes(item._id.toString());
});
resolve(docs);
});
});
}
/* GET home page. */
router.get('/', function (req, res, next) {
let cates, articles; // 目录,首要文章
let newArticles; // 叫近文章
let p1 = findCates();
let p2 = findArticles();
let promise = Promise.all([p1, p2]);
promise.then(function (items) {
// 以下两行代码其丑无比,不能直观的知道 items[0], items[1]是什么东西
cates = items[0];
articles = items[1];
// 获取最近文件列表
let excludeIDs = articles.map(item => item._id.toString());
findNewArticles(excludeIDs).then(function (result) {
newArticles = result;
render();
}).catch(function (err) {
throw err;
});
}).catch(function (err) {
throw err;
});
let render = function () {
console.log("index rendering...");
helper.formatDateTime(articles, { "createdTime": "YYYY/MM-DD" });
helper.formatDateTime(newArticles, { "createdTime": "YYYY/MM-DD" });
viewHelper.registerByName("_blog_summary")
viewHelper.registerByName("_article_item");
res.renderX('index', {
cates,
articles,
newArticles,
title: 'Express',
});
};
});
module.exports = router;