用Q实现一系列承诺

时间:2017-01-19 00:32:40

标签: javascript arrays mongodb promise q

当我在Mongodb数据库中搜索时,我试图通过查找分配给每个班次的人数来计算。然后我尝试将该值添加到shift数组中的shift对象中。不幸的是,代码似乎没有通过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部分中,我试图根据这些计数值对shift数组进行排序。这是我从console.log获得的消息(_。map(promiseList,&#39; promise&#39;)); :

[ { state: 'pending' },
  { state: 'pending' },
  { state: 'pending' },
  { state: 'pending' },
  { state: 'pending' },
  { state: 'pending' } ]
here1

1 个答案:

答案 0 :(得分:0)

问题中使用的Q库似乎不是承诺/ A + 1,因此不清楚为什么Q.all(...).then中的代码显然正在运行&#34;太快&# 34;

更改代码以使用本机Promise(现在在节点中可用)产生以下更整洁的代码 - 实际上有效!

dbFunctions.algorithm = function(collectionName, callback){
    var collection = dbConnection.collection(collectionName);

    var shifts = [ { value : 'setup' }, { value : '8:30' }, { value : '9:00' }, { value : '9:30' }, { value : '10:00' }, { value : 'cleanup' } ];

    Promise.all(shifts.map(function(shift) {
        return new Promise(function(resolve, reject) {
            collection.find({ 'Available[]' : { $elemMatch : { $eq : shift.value } } }).toArray(function(err, result) {
                shift.count = result.length;
                resolve();
            });
        });
    })).then(function(results) { // not actually used as the shifts array is updated directly
        shifts.sort(function (value1, value2){
            return value1.count - value2.count;
        });
        console.log(shifts);
    });
}