2016-01-20 106 views
0

我的目標是 1.提取唯一的數據 2.計算每個數據計算每一個數據時發生的NodeJS:異步結果爲了

async.waterfall([function(callback){ 
    var q = mongoose.model('student').distinct('hobby'); 
    q.exec(function(err,rst){ 
     callback(null,rst); 
    }); 
}, 
function(arg1,callback){ 
    var temp = new Array(); 
    async.map(arg1,function(val,callback1){ 
     var qq = mongoose.model('student').where('hobby').equals(val).count(); 
     qq.exec(function(err,rst){ 
      temp.push(rst); 
     }); 
     callback1(); 
    },function(e,r){}); 
    callback(null,temp); 
}], function(err,result){console.log("result:"+result);}); 

問題..

這是不一樣的順序與原來的array ..

回答

0

代碼中有幾個問題。回調不正確的地方。另外,應該使用async.mapSeries()而不是async.map()來保持數組的原始順序。這裏是修改後的代碼:

async.waterfall([ 
    function(callback){ 
    var q = mongoose.model('student').distinct('hobby'); 
    q.exec(function(err,rst){ 
     callback(null,rst); 
    }); 
    }, 
    function(arg1,callback){ 
    var temp = new Array(); 
    async.mapSeries(arg1,function(val,callback1){ 
     var qq = mongoose.model('student').where('hobby').equals(val).count(); 
     qq.exec(function(err,rst){ 
     temp.push(rst); 
     callback1(); // call here instead of outside 
     }); 
    },function(e,r){ 
     callback(null,temp); // call here instead of outside 
    }); 
    } 
], function(err,result){ 
    console.log("result:"+result); 
}); 
+1

謝謝,本!你真的拯救了我的一天:) – user2655470