I am trying to execute a callback in which only after getting the response it should execute the lines, starting from this.groupDefaultExpanded = -1; after that.
loadLoginDetails() {
this.derivativeSpecService.getDerivativeDetails().subscribe(
res => {
this.rowData = res;
this.groupDefaultExpanded = -1;
this.getDataPath = function(data) {
return data.orgHierarchy;
};
this.autoGroupColumnDef = {
headerName: "Name",
};
console.log(this.rowData);
})
}
derivativespec.ts
getDerivativeDetails(){
return this.http.get('assets/derivativespec.json').map((response: Response) => response);
}
Like this:
getDerivativeDetails(): Promise<Response> {
return this.http.get<Response>('assets/derivativespec.json').toPromise();
}
And then:
loadLoginDetails() {
this.derivativeSpecService.getDerivativeDetails().then(
res => {
this.rowData = res;
this.groupDefaultExpanded = -1;
this.getDataPath = function(data) {
return data.orgHierarchy;
};
this.autoGroupColumnDef = {
headerName: "Name",
};
console.log(this.rowData);
});
}
Related
What I currently have is 2 functions with callbacks.
At the end of validateEvent, there will be 2 variables isDeactivated and eventOrganizer.
While at the end of validateCheckIn, there will be 1 variable which is isCheckIn.
What I want to achieve now is merging the results of the 2 functions validateEvent and validateCheckIn into 1 new function where I can interact with 3 of the variables isDeactivated, eventOrganizer and isCheckIn in it.
What I've found so far is something like this: link
But what if I wanted to add extra code in the newly merged function?
var isDeactivated = false;
var eventOrganizer;
var isCheckIn = false;
function validateEvent(result) {
$.post(
"**displayEventAPI**",
{
id: eventID,
}).done(function (data) {
result(
data["eventList"][0]["event_status"],
data["eventList"][0]["event_creator"]
);
}
)
}
validateEvent(function(event_status, event_creator) {
if (event_status == 0) {
isDeactivated = true;
}
eventOrganizer = event_creator;
console.log(isDeactivated, '--isDeactivated');
console.log(eventOrganizer, '--eventOrganizer');
});
function validateCheckIn(result) {
$.post(
"**displayAttendanceAPI",
{
event_id: eventID,
}).done(function (data) {
for (var i = 0; i < data.attendanceList.length; i++) {
if (data.attendanceList[i].badge_id === badgeID) {
isCheckIn = true;
}
}
result(
isCheckIn
);
}
)
}
validateCheckIn(function(isCheckIn) {
console.log(isCheckIn, '--isCheckIn');
});
Try using Promise and async functions for the implementation.
Also wrap your async function calling inside an another async function. Because await keyword can only be used inside an async function.
var isDeactivated = false;
var eventOrganizer;
var isCheckIn = false;
async function validateEvent() {
return new Promise((resolve, reject) => {
$.post(
"**displayEventAPI**",
{
id: eventID,
}).done(function (data) {
resolve({
event_status: data["eventList"][0]["event_status"],
event_creator: data["eventList"][0]["event_creator"]
});
}
)
})
}
async function validateCheckIn(result) {
return new Promise((resolve, reject) => {
$.post("**displayAttendanceAPI", {
event_id: eventID,
}).done(function (data) {
for (var i = 0; i < data.attendanceList.length; i++) {
if (data.attendanceList[i].badge_id === badgeID) {
isCheckIn = true;
}
}
resolve(isCheckIn);
})
})
}
function thirdFunction(event_status, event_creator, isCheckIn) {
console.log(event_status, '--isCheckIn');
console.log(event_creator, '--isCheckIn');
console.log(isCheckIn, '--isCheckIn');
}
async function execute() {
const { event_status, event_creator } = await validateEvent();
const isCheckIn = await validateCheckIn();
thirdFunction(event_status, event_creator, isCheckIn);
}
execute();
I need to fix the error on code below, can someone help me please?. The code is written on JS(NodeJs). The error is this (...).then is not a function. Thanks.
try {
var decoded = jwt.decode(JWTToken, { complete: true });
var audience = decoded.payload.aud;
return db.checkAudience(audience).then(ehClient => {
if (ehClient == true) {
return db.getCreditsGeneral(sgecode, collections, year).then(total => {
let result = [];
total.forEach(item => {
result.push({
collection: item.Sistema,
levelType: item.idNivelEnsino,
grade: item.codPortal
});
});
return result;
});
} else {
return "not authorized";
}
});
} catch (err) {
return { erro: err.message };
}
User.find({ refUser: req.params.userName }).then(function (users) {
var network_users = [];
network_users.push(users);
users.forEach(function (u) {
network_users.push(User.find({ refUser: u.toObject().userName }));
})
return Promise.all(network_users);
I have 4 users, I expected receive a json with all of childrens but I only received the first and the children of this first.
Someone can help me with this loop? Please! Thanks so much!!!!
function asyncLoop(iterations, func, callback, foo) {
var done = false;
var loop = {
next: function () {
if (done) {
return;
}
if (iterations) {
func(loop);
} else {
done = true;
if (callback) callback(foo);
}
},
isEnd: function () {
return done;
},
refresh: function (it) {
iterations = it;
},
break: function () {
done = true;
callback();
}
};
loop.next();
return loop;
}
function bfs(userName, callback) {
userName = String(userName);
var q = [], res = [];
User.findOne({ "refUser" : userName }).lean().exec(function (err, root) {
root.depth = 0;
q.push(root);
asyncLoop(q.length, function (loop) {
res.push(q[0]);
User.find({ "refUser" : q[0].userName }).lean().exec(function (err, new_nodes) {
if (err) console.log(err);
else {
var d = q[0].depth;
q.shift();
loop.refresh(new_nodes.length + q.length);
if (new_nodes.length > 0) {
new_nodes.forEach(function (new_node) {
new_node.depth = d + 1;
q.push(new_node);
});
}
loop.next();
}
});
}, function () { callback(res) });
});
}
Finishing:
bfs(req.params.userName,function(callback){
res.send(callback)
})
I have two js files. i am able to get data from mongodb by calliing bookDao.getActiveBookByCategoryId().
My Problem
In categoryDao.js file i am trying to update resultJson.book_countinside BookDao.getActiveBookByCategoryId() method. but it is not updating. So may i know how to fix this.
here book_count property in resultJson is still 0.
categoryDao.js
module.exports.getAllActiveCategory = (callback) => {
Category.find({
is_delete : false
}, (error, result) => {
if(error) {
console.log(error);
callback(commonUtil.ERROR);
}
if(result) {
var categoryArray = [];
for(var i=0; i<result.length; i++) {
var categorySingle = result[i];
var resultJson = {
_id : categorySingle._id,
category_name : categorySingle.category_name,
created_on : categorySingle.created_on,
book_count : 0
}
BookDao.getActiveBookByCategoryId(categorySingle._id, (bookResult) => {
if(bookResult) {
if(bookResult.length > 0) {
resultJson.book_count = bookResult.length;
}
}
});
categoryArray.push(resultJson);
}
callback(categoryArray);
}
});
}
bookDao.js
module.exports.getActiveBookByCategoryId = (categoryId, callback) => {
Book.find({
is_delete : false,
category : categoryId
}, (error, result) => {
if(error) {
console.log(error);
callback(commonUtil.ERROR);
}
if(result) {
callback(result);
}
});
}
Try this, In your code categoryArray.push(resultJson); will not wait for BookDao.getActiveBookByCategoryId to finish because of async behavior.
module.exports.getActiveBookByCategoryId = (categoryId) => {
return Book.count({
is_delete: false,
category: categoryId
});
}
module.exports.getAllActiveCategory = async () => {
try {
// Find all category
const result = await Category.find({
is_delete: false
});
// Create array of promise
const promises = result.map(categorySingle => BookDao.getActiveBookByCategoryId(categorySingle._id));
// Get array of Category count
const data = await Promise.all(promises);
// update count in result
return result.map((categorySingle, i) => {
categorySingle.book_count = data[i];
return categorySingle;
});
} catch (error) {
console.log(error);
}
}
I'm using bluebird in NodeJS. I want to do a nested loop. Something like this:
var Promise = require('bluebird');
funcs.getLatestVideos = function(job, done) {
return Promise.try(function() {
return ProcessRules.getLatestVideos();
})
.then(function(object) {
return ({
'series': ProcessRules.getSeriesRules(),
'videos': object.videos
});
})
.then(function(inputs) {
return Promise.map(inputs.videos, function(video) {
return Promise.map(inputs.series, function(series) {
return Promise.map(series.rules, function(rule) {
return ProcessRules.processRules(video, rule);
});
});
})
})
.then(function(result) {
W.debug("done");
console.log(JSON.stringify(result));
done();
})
.catch(function(err) {
done(err);
W.error("Error occurred ", err.message, err.stack);
});
}
ProcessRules
var Promise = require('bluebird');
var rp = require('request-promise');
var W = require('winston');
var RuleEngine = require('node-rules');
var _ = require('lodash');
funcs.getSeriesRules = function() {
return new Promise(function(resolve, reject) {
var options = {
method: "GET",
uri: API_URL,
// body: status,
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function(result) {
resolve(result)
})
.catch(function(err) {
reject(err)
});
});
};
funcs.processRules = function(fact, rule) {
return new Promise(function(resolve, reject) {
var rules = [];
var value = new RegExp(rule.value, 'i');
switch (rule.type) {
case 'title':
rules = [{
"condition": function(R) {
// console.log(this.title.match(value));
R.when(this.title.match(value) > -1);
},
"consequence": function(R) {
this.result = false;
this.video = R;
R.stop();
}
}];
break;
case 'desc':
rules = [{
"condition": function(R) {
//console.log(this.desc.match(value));
R.when(this.desc.match(value) > -1);
},
"consequence": function(R) {
this.result = false;
this.video = R;
R.stop();
}
}];
break;
case 'tag':
rules = [{
"condition": function(R) {
// console.log(this.tag.match(value));
R.when(!_.some(this.tags, { 'text': rule.value}))
},
"consequence": function(R) {
this.result = false;
this.video = R;
R.stop();
}
}];
break;
default:
break
};
//initialize the rule engine
const R = new RuleEngine(rules);
//Now pass the fact on to the rule engine for results
R.execute(fact, function(result) {
//console.log(result);
if (result.result) {
resolve(result._id)
}else{
resolve({})
}
});
});
};
It returns me following output
[[[{},{},"58e9d6816961c30367b5154c"],[{}],[],[],[]],[[{},{},"58e9d6816961c30367b5154d"],[{}],[],[],[]]]
But I am expecting with following output:
[58e9d6816961c30367b5154c,58e9d6816961c30367b5154d]
I see some similar question but not getting exact ideas from them.
In getLatestVideos function not able to get done result ,Please help me to resolve this issue.
Please help me to implement nested each loop with bluebird promise.
After long search with multiple questions and answers , I got the answer by Flattening a Promise map.
I don't know exactly its right way but its working for me.
.then(function(inputs) {
return Promise.map(inputs.videos, function(video) {
return Promise.map(inputs.series, function(series) {
return Promise.map(series.rules, function(rule) {
return ProcessRules.processRules(video, rule);
}).reduce(function(prev, cur) {
return cur ? prev.concat(cur) : [];
}, [])
}).reduce(function(prev, cur) {
return prev.concat(cur);
}, [])
}).reduce(function(prev, cur) {
return prev.concat(cur);
}, [])
})
It returns me [58e9d6816961c30367b5154c,58e9d6816961c30367b5154d].
Thanks Everyone.