node.js - async.each 배열 항목 정렬 순서 자동 변경
문제
ASYN 라이브러리가있는 node.js를 사용하고 있습니다 ( https://github.com/caolan/async./a>).async.each 함수를 사용하면 잘 작동하지만 배열 항목 주문을 변경하여 일부 정렬과 함께 범주를 나열 할 수 없습니다 ..
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.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 ()를 사용할 수 있습니다.카테고리).
다른 팁
문서에서 :
이 함수는 병렬로 각 항목에 반복자를 적용하기 때문에 반복자 기능이 순서대로 완료 될 것이라는 보장이 없습니다.
처리 후 배열을 정렬하지 않는 이유는 무엇입니까?
예 :
function compareByName(row1, row2) {
if (row1.name > row2.name) {
return 1;
}
return row1.name === row2.name ? 0 : -1;
}
categories.sort(compareByName);
.
또는 마지막 밀리 초를 요청하지 않으면 대신 eachSeries
를 사용할 수 있습니다.
btw new Array()
로 많은 {}
를 대체해야한다고 생각합니다.
제휴하지 않습니다 StackOverflow