myTest 里的数据:{id:1,name:’a’},{id:2,name:’b’},{id:3,name:’c’}; 我想对idArr中的每一个id通过get查找返回list或者result,get方法里又是异步(或者get里面会更加复杂),这么写只能查到id:3, 求教大神怎么解决
var mongodb = require('./db');
function asyncTest() {
var idArr = [1, 2, 3];
/*
eventproxy
*/
var Eventproxy = require('eventproxy');
var ep = new Eventproxy();
ep.after('find', idArr.length, function (list) {
console.log('this is the final')
console.log(list)
});
for (var i = 0; i < idArr.length; i++) {
console.log('for loop'+i)
get(idArr[i], function (err, results) {
ep.emit('find', results);
console.log('result'+results)
});
}
/*
async
*/
var async = require('async');
async.map(idArr,function(id,cb){
get(id,function(err,results){
if(err){
}
cb(null,results);
})
}),function(err,results){
if(err){
}
console.log('result'+results);
}
}
function get (req,cb){
console.log(req+'find');
mongodb.close();
mongodb.open(function(err,db){
if(err){
}
console.log(req+'find col');
db.collection('myTest',function(err,collection){
if(err){
console.log(err)
}
collection.find({id:req}).toArray(function(err,doc){
if(err){
console.log(err);
}
console.log(doc)
cb(err,doc)
})
})
})
}
asyncTest();