【发布时间】:2017-06-03 13:34:44
【问题描述】:
我试图通过在我的 Mongodb 数据库中搜索时找到分配给每个班次的人数来计算分配给每个班次的人数。然后我试图将该值添加到我的班次数组中的班次对象。不幸的是,代码似乎没有通过 Q.all 部分进行。我对 promises 或 Q 的概念不是很熟悉,所以我不确定我是否犯了一个非常粗心的错误。
dbFunctions.algorithm = function(collectionName, callback){
var collection = dbConnection.collection(collectionName);
//order the shifts in order of number of volunteers
var shifts = [ { value : 'setup' }, { value : '8:30' }, { value : '9:00' }, { value : '9:30' }, { value : '10:00' }, { value : 'cleanup' } ];
var promiseList = [];
for(var i=0; i < shifts.length; i++) {
promiseList[i] = Q.defer();
}
for ( var j=0; j<shifts.length; j++ ){
var promise=promiseList[j];
var shift = shifts[j];
collection.find({ 'Available[]' : { $elemMatch : { $eq : shift.value } } }).toArray(function(err, result) {
shift.count = result.length;
promise.resolve();
});
}
console.log(promiseList);
console.log(_.map(promiseList,'promise'));
console.log("here1");
Q.all(_.map(promiseList,'promise')).then(function(value){
console.log("here2");
shifts.sort(function (value1, value2){
return value1.count - value2.count;
});
console.log(shifts);
});
}
在代码的 Q.all 部分中,我尝试根据这些计数值对移位数组进行排序。这是我从 console.log(_.map(promiseList,'promise')); 得到的消息:
[ { state: 'pending' },
{ state: 'pending' },
{ state: 'pending' },
{ state: 'pending' },
{ state: 'pending' },
{ state: 'pending' } ]
here1
【问题讨论】:
-
如果将
Q.all(_.map(promiseList,'promise'))更改为Q.all(promiseList)效果会更好吗? -
当我这样做时,它会通过代码的 Q.all 部分;但是,它只打印出:here2 [ { value: 'setup' }, { value: '8:30' }, { value: '9:00' }, { value: '9:30' }, { value : '10:00' }, { value: 'cleanup' } ]
-
所以计数没有被存储并且数组没有被排序
-
我现在看到了问题...您确定.count 绝对没有变化吗?我相信最后一个会拥有它
-
检查代码 - 在this fiddle - 是否符合您的要求?
标签: javascript arrays mongodb promise q