2017-01-19 10 views
0

私はMongodbデータベースで検索したときに各シフトに割り当てられた個体の数を数えます。私はシフト・アレイ内のシフトのオブジェクトにその値を追加しようとしています。残念ながら、コードがQ.allセクションを進んでいるとは思われません。私は約束やQの概念に慣れていないので、私が非常に不注意なエラーを出したかどうかはわかりません。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 
+0

Q.all(promiseList、 'promise')) 'を' Q.all(promiseList) 'に変更した方がうまく機能しますか? –

+0

私はこれを行うと、コードのQ.allセクションを通過します。ここでは、これだけが表示されます:here2 [{値: 'セットアップ'}、 {値: '8:30'}、 {値: '9:00'}、 {値: '9:30' }、 {値:'10:00 '}、 {値:'クリーンアップ '}] – user7438390

+0

カウントが保存されておらず、配列がソートされていない – user7438390

答えて

0

問題で使用されるQライブラリは約束/ A + 1ではないと思われるので、Q.all(...).thenのコードは明らかにコードを変更

「早すぎる」実行されている理由は明らかではありませんネイティブ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); 
    }); 
}