首页 > 代码库 > 避免多层回调,Node.js异步模块Async初使用

避免多层回调,Node.js异步模块Async初使用

原来写的一个分页查询,回调了好几层。

exports.list = function(req,res) {    var params = {};    var current_page = common_util.get_param_value(req,‘current_page‘,‘Number‘,1);    var page_size = common_util.get_param_value(req,‘page_size‘,‘Number‘,10);    var start_index = common_util.get_start_index(current_page,page_size);    Topic.find(params).skip(start_index).limit(page_size).sort({‘reply_time‘:-1}).exec(function(err,docs){        if(err) {            console.error(err);        }else {            Topic.count(params,function(err,count){                if(err){                    console.error(err);                }else{                    docs.forEach(function(doc){                        doc.interval = date_util.interval(doc.last_reply_time);                    });                    Category.find({}, function (err, categoryList) {                        if (err) {                            console.error(err);                        } else {                            var result = {};                            result.current_page = current_page;                            result.page_size = page_size;                            result.total_count = count;                            resutl.total_page = common_util.get_total_page(count,page_size);                            result.datas = docs;                            result.categoryList = categoryList;                            console.dir("hello");                            console.dir(result);                            res.render(‘index‘, result);                        }                    });                }            });        }        });}

 

使用Async后,代码如下:

exports.list = function(req,res) {    var params = {};    var current_page = common_util.get_param_value(req,‘current_page‘,‘Number‘,1);    var page_size = common_util.get_param_value(req,‘page_size‘,‘Number‘,10);    var start_index = common_util.get_start_index(current_page,page_size);    async.parallel({       datas:function(cb){           Topic.find(params).skip(start_index).limit(page_size).sort({‘reply_time‘:-1}).exec(function(err,docs){               cb(err,docs);           });       },       total_count:function(cb){           Topic.count(params,function(err,count){               cb(err,count);           });       },       categoryList:function(cb){           Category.find({}, function (err, categoryList) {               cb(err,categoryList);           });       }    },function(err,results){        if(err){            console.error(err);        }else{            results.current_page = current_page;            results.page_size = page_size;            results.total_page = common_util.get_total_page(results.total_count,page_size);            res.render(‘index‘, results);        }    });}

 

 

async.parallel,并行执行。支持json格式任务,返回的数据也是json格式,json字段的顺序按照任务字段的排序。
{ datas:    [ { _id: 539c156dce6d3ea40f1f1d15,       author: ‘yekai‘,       content: ‘<p>\n\t<span style="font-family:微软雅黑, Tahoma, Verdana, 宋体;font-size:16px;line-height:26px;background-color:#FFFFFF;">由于网站刚刚建立,并没有提供什么特别的内容,仅仅是将官方主页的内容翻译过来而已,而且也有部分的错误,不过相信以后该网站会成为了解Ubuntu在中国的动态的一个窗 口。</span>\n</p>\n<p>\n\t<span style="font-family:微软雅黑, Tahoma, Verdana, 宋体;font-size:16px;line-height:26px;background-color:#FFFFFF;"><img src="http://static.cnbetacdn.com/newsimg/2014/0613/25_1jCLSOQac.png_w600.png"  /><br />\n</span>\n</p>‘,       category: ‘other‘,       title: ‘Ubuntu 中国官网现已面世‘,       __v: 1,       last_reply_time: Tue Jun 17 2014 21:54:33 GMT+0800 (中国标准时间),       last_reply_username: ‘yekai‘,       reply_amount: 2,      },     { _id: 53a04500e5cb4710178753a5,       last_reply_username: ‘yekai‘,       last_reply_time: Tue Jun 17 2014 21:44:52 GMT+0800 (中国标准时间),       author: ‘yekai‘,       content: ‘赌球输了‘,       category: ‘world_cup‘,       title: ‘德国赢了‘,       __v: 2,       reply_amount: 3,      },     { _id: 539c16fe9e359e841cc1b097,       author: ‘yekai‘,       content: ‘<p>\n\t<span style="color:#434343;font-family:微软雅黑, Tahoma, Verdana, 宋体;font-size:16px;line-height:24px;background-color:#FBFBFB;">据国外媒体报道,研究人员最新研究表明,地球最大蓄水层位于美国境内之下的地幔层,大约在地下643.7公里(400英里)处。</span>\n</p>\n<p>\n\t<span style="color:#434343;font-family:微软雅黑, Tahoma, Verdana, 宋体;font-size:16px;line-height:24px;background-color:#FBFBFB;"><img src="http://static.cnbetacdn.com/newsimg/2014/0614/51_1jCUT0h0z.jpg_w600.jpg"  /><br />\n</span>\n</p>‘,       category: ‘other‘,       title: ‘美国地下643.7公里发现地球最大“蓄水池”‘,       __v: 2,       last_reply_time: Tue Jun 17 2014 22:06:43 GMT+0800 (中国标准时间),       last_reply_username: ‘afei‘,       reply_amount: 3,       } ],  total_count: 3,  categoryList:    [ { _id: 5397181a1f7f534418cbbd84,       desc: ‘Java类别‘,       code: ‘Java‘,       name: ‘Java‘,       __v: 0 },     { _id: 53971d90e209ea6414b2819f,       desc: ‘‘,       code: ‘Nodejs‘,       name: ‘Nodejs‘,       __v: 0 },     { _id: 5399b429a068211816605fbb,       desc: ‘‘,       code: ‘world_cup‘,       name: ‘世界杯‘,       __v: 0 },     { _id: 539c1526ce6d3ea40f1f1d14,       desc: ‘‘,       code: ‘other‘,       name: ‘其他‘,       __v: 0 } ],  current_page: 1,  page_size: 10,  total_page: 1 }