node.js – async.each数组项sorting顺序自动更改

我使用asynchronous库( https://github.com/caolan/async)node.js 。 当我使用async.each函数其工作正常,但它更改数组项目订单,所以我不能列出类别与一些sorting..

module.exports = { index: function (req, res) { var async = require('async'); var data = new Object(); data.title = ""; data.meta_keywords = ""; data.meta_description = ""; data.category = new Array(); bredcrumbs = new Array(); bredcrumbs[0] = {'text':'Home','link':'Link','active':false}; category_list = new Array(); categories = new Array(); async.waterfall([ function(callback){ Category.find({sort: 'name ASC'}).done(function(err,cat_data){ //console.log(cat_data); categories = cat_data; callback(null); }); }, function(callback){ async.each(categories, SaveData, function(err){ // if any of the saves produced an error, err would equal that error callback(null); }); }, ], function () { data.category = category_list; //console.log(category_list); res.view('pages/home',data); }); function SaveData(item,callback){ Word.count({category_id:item['id'],status:'1',is_approved:'1'}).done(function(err, total){ t_category = new Array(); t_category['name'] = item['name']; t_category['keyword'] = item['keyword']; t_category['link'] = "http://"+req.headers.host+"/game/"+item['keyword']; t_category['total'] = total; category_list.push(t_category); callback(null); }); } }, /** * Overrides for the settings in `config/controllers.js` * (specific to HomeController) */ _config: {} }; 

我正在使用async.eachfunction

  async.each(categories, SaveData, function(err){ // if any of the saves produced an error, err would equal that error callback(null); }); 

async.each()不是在串行执行SaveData(),所以如果你想保持新数组(category_list)的项目与原始数组(类别)相同的顺序,你可能想要使用async.eachSeries()。

从文档:

请注意,由于此函数并行地将迭代器应用于每个项目,因此不能保证迭代器函数将按顺序完成。

为什么不在处理之后对数组进行sorting呢?

例:

 function compareByName(row1, row2) { if (row1.name > row2.name) { return 1; } return row1.name === row2.name ? 0 : -1; } categories.sort(compareByName); 

或者,如果您不需要按最后一毫秒的请求,则可以使用eachSeries

顺便说一句,我想你应该用{}来replace你的new Array()