I want to add have nested DB query inside a eachOf loop which should be synchronous. Tried so many combinations and which but nothing works for inside of foreach loop.
async.eachOf(nc.virtual_devices, function (vd) {
///////// This code work fine /////////////
var domain = extractDomain(vd.api_url);
vd.raw_api_ip = vd.api_ip;
vd.api_ip = getProxiedPath(vd.api_ip);
vd.raw_api_url = vd.api_url;
vd.api_url = nconf.get('PROXIED_PATH_SCHEME') + vd.api_ip + vd.api_url.split(domain)[1];
// Path to websocket notifications
vd.ws_url = nconf.get('PROXIED_PATH_SCHEME') + vd.api_ip + vd.notification_base_uri;
//// THIS CODE IS NOT FINE //////////////
if (nc.type === 'XXX'){
var promise = new Promise (function (resolve,reject) {
console.log("********XX VD TYPE **********");
console.log(JSON.stringify(vd));
console.log("VD ID VALUE IS ", vd.id);
var newID = (vd.id).replace(/\d_/, "");
console.log("VD ID VALUE IS ", newID);
var _idofSubgroup;
var labeltoSearch = nc.type + ' ' + nc.version;
pattern = "/^" + newID + "/i";
test = _idofSubgroup;
pattern = newID;
console.log(pattern);
db.collection('subgroups').findOne({label: labeltoSearch}, function (err, result) {
console.log(result._id);
_idofSubgroup = result._id;
db.collection('exploreposts').find({subgroup: result.id_}, {title: {"$regex": pattern}}).toArray(function (err, results) {
console.log(results);
})
});
})
}
});
Tried with promise inside it but that also in pain. This is my tried code which is not working fine. Any suggestion would be appreciated., as simply said i have been stuck in callback hell
async.eachOf(nc.virtual_devices, function (vd) {
///////// This code work fine /////////////
var domain = extractDomain(vd.api_url);
vd.raw_api_ip = vd.api_ip;
vd.api_ip = getProxiedPath(vd.api_ip);
vd.raw_api_url = vd.api_url;
vd.api_url = nconf.get('PROXIED_PATH_SCHEME') + vd.api_ip + vd.api_url.split(domain)[1];
// Path to websocket notifications
vd.ws_url = nconf.get('PROXIED_PATH_SCHEME') + vd.api_ip + vd.notification_base_uri;
//// THIS CODE IS NOT FINE with promises also //////////////
if (nc.type === 'XXX'){
var promise = new Promise (function (resolve,reject) {
console.log("********XX VD TYPE **********");
console.log(JSON.stringify(vd));
console.log("VD ID VALUE IS ", vd.id);
var newID = (vd.id).replace(/\d_/, "");
console.log("VD ID VALUE IS ", newID);
var _idofSubgroup;
var labeltoSearch = nc.type + ' ' + nc.version;
pattern = "/^" + newID + "/i";
test = _idofSubgroup;
pattern = newID;
console.log(pattern);
db.collection('subgroups').findOne({label: labeltoSearch}, function (err, result) {
console.log(result._id);
_idofSubgroup = result._id;
resolve ({id_:_idofSubgroup,pattern1 : pattern});
})
});
promise.then (function(result) {
console.log(result.id_);
console.log(result.pattern1);
db.collection('exploreposts').find({subgroup: result.id_}, {title: {"$regex": result.pattern1}}).toArray(function (err, results) {
console.log(results);
})
},function (err){
console.log (err);
})
}
});