I am having trouble with listsQuery not executing by the time everything gets sent to the browser. I know I need a Promise or something in there, but my attempts are so far unsuccessful. Help!
function processNavigation(navigation) {
var nav = [];
_.each(navigation, function(navItems) {
var navProperties = {
name: navItems.get("Name"),
longName: navItems.get("LongName"),
icon: navItems.get("Icon"),
url: navItems.get("Url"),
module: navItems.get("Module"),
runScript: navItems.get("RunScript"),
sortOrder: navItems.get("SortOrder")
};
switch (navItems.get("Module")) {
case "lists":
var listsQuery = new Parse.Query("ListItems"); // This should return back! But it's async? Needs promise?
listsQuery.ascending("SortOrder");
listsQuery.find().then(
function(results) {
var list = [];
_.each(results, function(listItems) {
var listProperties = {
name: listItems.get("Name"),
subName: listItems.get("Subname"),
sortOrder: listItems.get("SortOrder")
};
});
list.push(listProperties);
navProperties["source"] = list;
},
function() {
res.send('error');
}
);
break;
default:
navProperties["source"] = null;
break;
}
nav.push(navProperties);
});
res.send(nav);
}
This should give you something to go on, im not sure if it will work but it should show you the concept.
What you need to do is create an array of promises as it looks like your performing a query for each item in an array, and because the queries take some time your response is sent before the queries are complete. You then evaluate the array of promises and send your response back only when they are resolved.
I would suggest you split your logic into a few more functions as it's a little hard to follow.
Take a look at the parallel promises section
function processNavigation(navigation) {
var nav = [];
var promises = []
_.each(navigation, function(navItems) {
var navProperties = {
name: navItems.get("Name"),
longName: navItems.get("LongName"),
icon: navItems.get("Icon"),
url: navItems.get("Url"),
module: navItems.get("Module"),
runScript: navItems.get("RunScript"),
sortOrder: navItems.get("SortOrder")
};
switch (navItems.get("Module")) {
case "lists":
promises.push((function(navProperties){
var listsQuery = new Parse.Query("ListItems"); // This should return back! But it's async? Needs promise?
listsQuery.ascending("SortOrder");
listsQuery.find().then(
function(results) {
var list = [];
_.each(results, function(listItems) {
var listProperties = {
name: listItems.get("Name"),
subName: listItems.get("Subname"),
sortOrder: listItems.get("SortOrder")
};
});
list.push(listProperties);
navProperties["source"] = list;
promise.resolve();
},
function() {
promise.reject();
res.send('error');
}
);
})(navProperties))
break;
default:
navProperties["source"] = null;
break;
}
nav.push(navProperties);
});
Parse.Promise.when(promises).then(function(){
res.send(nav);
})
}
Related
I want to draw 5 graph a single page based on different condition. Actually I am using a loop and send different data each time and based on that condition I want to create a graph. But don't know why the library d3.js is only trigger the draw function in the end and create a single graph based on last condition. also I am using apache wicket framework
I call the function 5 time using a loop and send different data
final def rawData(id:String): String = {
s"""
require(["renderer"], function (renderer) {
renderer.init("#${id}");
var data = 'digraph g {\\n ${data.attributes.trim} \\n' +
${if (nodes.isEmpty) "''" else nodes} +
${if (links.isEmpty) "''" else links} +
'}';
const getData = async() => {
await renderer.render(data);
}
getData();
});
"""
}
Upper function trigger the below function but in below function init function is call each time and set the data in javascript . Also render function is also call each time but it is not going to ready stage each time it is going in pending and in last it trigger the ready stage and draw the last graph only.
define('renderer',["stage", "worker!layout-worker.js"], function(stage, worker) {
var initialized = false, pending, errorCallback, renderCallback;
var bool =false;
worker.onmessage = function (event) {
switch (event.data.type) {
case "ready":
initialized = true;
if (pending) {
worker.postMessage(pending);
}
break;
case "stage":
stage.draw(event.data.body);
console.log("stage =================> ",event.data.type);
renderCallback && renderCallback();
break;
case "error":
if (errorCallback) {
errorCallback(event.data.body);
}
}
};
return {
init: function(element) {
return stage.init(element);
},
render: function(source) {
if (initialized) {
worker.postMessage(source);
} else {
pending = source;
}
},
stage: stage,
errorHandler: function(handler) {
errorCallback = handler;
},
renderHandler: function(handler) {
renderCallback = handler;
}
};
});
require(/*{
baseUrl: "."
},*/
["transformer"],
function(transformer) {
onmessage = function(event) {
try {
var result = transformer.generate(event.data);
postMessage({
type: "stage",
body: result
});
} catch (e) {
postMessage({
type: "error",
body: e
});
}
};
postMessage({
type: "ready"
});
}
);
How to ensure, in JavaScript (jquery) that some actions are performed one after other, in an order.
Say, I need to load schools collection BEFORE loading teachers, in order to assing the myTeacher.SchoolName = schools[myTeacher.SchoolId].name;
The pseudo code bellow:
const studentsUrl='api/students', teachersUrl='api/teachers', schoolsUrl='api/schools';
let students = null, teachers = null, schools = null;
$(document).ready(function () {
getSchools();
getTeachers();
getStudents();
});
function getSchools() {
$.get(schoolsUrl, function (data) {
window.schools = data;
});
}
function getTeachers() {
$.get(teachersUrl, function (data) {
window.teachers = data;
// >>> SHOULD BE SURE, SCHOOLS already loaded!!!
$.each(teachers, function (key, item) {
item.school = schools[item.schoolId].name;
});
});
}
function getStudents() {
$.get(studentsUrl, function (data) {
window.students = data;
// >>> SHOULD BE SURE, TEACEHRS already loaded!!!
$.each(students, function (key, item) {
item.teacher = teachers[item.teacherId].name;
});
});
}
PS.
Is there another way to assure order but the encapsulation of one function at the end of another?
As others already suggested you can chain requests.
I made few changes to your code.
Added Strict Mode it helps to prevent bugs
The code wrapped in IFFE in order to prevent global pollution
If all apis belong to the same server you can process all this data on server side
and return one filled json.
in this way your server will do a little extra work on constructing this json but in other hand you will make only one ajax request instead of 3.
This will work faster and you can cache this json for some time
Code for the first solution
(function () {
'use strict';
const studentsUrl = 'api/students';
const teachersUrl = 'api/teachers';
const schoolsUrl = 'api/schools';
let students = null;
let teachers = null;
let schools = null;
var scoolData = {
schools: null,
teachers: null,
students: null
};
$(document).ready(function () {
getSchools().then(function (schools) {
scoolData.schools = schools;
getTeachers().then(function (teachers) {
scoolData.teachers = teachers;
$.each(scoolData.teachers, function (key, item) {
item.school = scoolData.schools[item.schoolId].name;
});
});
});
});
function getSchools() {
return $.get(schoolsUrl);
}
function getTeachers() {
return $.get(teachersUrl,
function (result) {
scoolData.teachers = result;
// >>> SHOULD BE SURE, SCHOOLS already loaded!!!
$.each(teachers, function (key, item) {
item.school = scoolData.schools[item.schoolId].name;
});
});
}
})();
Since you only need all the results available and each request does not depend on the previous you can use jQuery.when
let students = null;
let teachers = null;
let schools = null;
$(document).ready(function() {
$.when(
getSchools(),
getTeachers()
).done(function(shoolResults, teacherResults) {
window.schools = shoolResults;
window.teachers = teacherResults;
handleTeachers();
getStudents();
});
function getSchools() {
return $.ajax({
type: 'GET',
url: schoolsUrl
});
}
function getTeachers() {
return $.ajax({
type: 'GET',
url: teachersUrl
});
}
function handleTeachers() {
$.each(teachers, function (key, item) {
item.school = schools[item.schoolId].name;
});
}
});
If you want them in order (though I'm not sure I understand why, since you retrieve all schools/teachers/students anyway), you can simply do this.
Note: get* functions are dummies in the following sample. Instead, just return the result of $.get calls from them:
function getSchools() {
return Promise.resolve({1: {name: 'school1'}});
}
function getTeachers() {
return Promise.resolve({1: {name: 'teacher1', schoolId: 1}});
}
function getStudents() {
return Promise.resolve({1: {name: 'student1', teacherId: 1}});
}
(async () => {
const schools = await getSchools();
const teachers = await getTeachers();
const students = await getStudents();
// Alternative for the $.each code
Object.values(teachers).forEach(teacher => teacher.school = schools[teacher.schoolId].name);
Object.values(students).forEach(student => student.teacher = teachers[student.teacherId].name);
console.log(schools, teachers, students);
})();
Another note: this is ES8 code, I'll post a non async/await version if you need to support older browsers and can't use a transpiler like Babel.
Non ES8-dependent code:
function getSchools() {
return Promise.resolve({1: {name: 'school1'}});
}
function getTeachers() {
return Promise.resolve({1: {name: 'teacher1', schoolId: 1}});
}
function getStudents() {
return Promise.resolve({1: {name: 'student1', teacherId: 1}});
}
let schools = null, teachers = null, students = null;
getSchools().then(_schools => {
schools = _schools;
return getTeachers();
}).then(_teachers => {
teachers = _teachers;
return getStudents();
}).then(_students => {
students = _students;
for (var _ in teachers) {
teachers[_].school = schools[teachers[_].schoolId].name;
}
for (var _ in students) {
students[_].teacher = teachers[students[_].teacherId].name
}
console.log(schools, teachers, students);
});
Call getTeachers(); when getSchools(); return success or complete, success preferred since complete runs if there's an error..
I think you are looking for this one.
getSchools().done(function(data){
var someId = data.findThatId;
getTeachers(someId);
});
You will need to return data from ajax call to get data in done.
You may load them asynchronously but you have to wait until both calls are finished.
To achieve this, add return before your ajax calls and combine the results in your ready function (not in the success handler of the teachers call):
let schoolsPromise = getSchools();
let teachersPromise = getTeachers();
$.when(schoolsPromise, teachersPromise)
.then((schools, teachers) => {
$.each(teachers, (key, item) => {
item.school = schools[item.schoolId].name;
});
});
I'm having a small issue using RxJS and Angular (not Angular 2) that I'm sure indicates I'm just doing something wrong, but I'm not sure exactly what.
I have a function that creates an rx.Observable stream that I would like to test. A simplified version of the function is below:
ResourceCollection.prototype.rxFetch = function() {
var scheduler = this.injectedScheduler;
var result = functionThatReturnsAnObservable(theseParams).concatMap(function(items) {
var promises = _.map(readFromExternal(items), function(promise) {
// results of this promise should be ignored
return Rx.Observable.fromPromise(promise, scheduler);
});
promises = promises.concat(_.map(items, function(item) {
// callEvent returns EventResult, these values should be passed on
return Rx.Observable.fromPromise(callEvent(item), scheduler);
}));
return promises;
}).concatMap(function(x) { return x; }).filter(function(res) {
return (res instanceOf EventResult);
}).toArray();
return result;
});
My test function looks like this:
describe('query', function() {
var customers;
var scheduler;
beforeEach(function() {
scheduler = new Rx.TestScheduler();
customers = new ResourceCollection({
url: '/api/customers',
keyName: 'CustomerId',
globalActions: {
rxQuery: { method: 'GET', isArray: true }
}
});
$httpBackend.whenGET('/api/customers/rxQuery').
respond(function() {
return [200, [
{ CustomerId: 1, Name: 'Brian', Region: 'North' },
{ CustomerId: 2, Name: 'Ravi', Region: 'East' },
{ CustomerId: 3, Name: 'Ritch', Region: 'East' },
{ CustomerId: 4, Name: 'Jeff', Region: 'West' },
{ CustomerId: 5, Name: 'Brandon', Region: 'West' }
]];
});
});
it('rxFetch customers', function(done) {
var vals;
customers.injectedScheduler = scheduler
var result = customers.rxFetch();
result.subscribe(function(values) {
vals = values;
});
$httpBackend.flush();
// my question is here - what can I do to get rid of this loop?
while (vals == null) {
scheduler.advanceBy(100);
$rootScope.$apply();
}
scheduler.start();
expect(vals.length).toEqual(5);
expect(vals[0]).toBe(customers[0]);
done();
});
});
The issue is a simple one - while the while loop in the test is in there, the test will produce the correct results (which is an array that contains the results of all the callEvent functions). Replace the while loop with a scheduler.scheduleAbsolute (or some other such call) combined with a $rootScope.$apply, and only one of the promises from the callEvent function will complete. Call it twice, and two of them will complete, etc (hence the while loop).
But the while loop is pretty ugly - and I'm sure there has to be an cleaner way to get this test to pass. Many thanks to anyone who can point me in the correct direction.
I have some JavaScript code:
var findLeastUsedPassage;
findLeastUsedPassage = function(StudentId) {
var passageCounts;
passageCounts = [];
return db.Passage.findAll({
where: {
active: true
}
}).each(function(dbPassage) {
var passage;
passage = dbPassage.get();
passage.count = 0;
return passageCounts.push(passage);
}).then(function() {
return db.Workbook.findAll({
where: {
SubjectId: 1,
gradedAt: {
$ne: null
},
StudentId: StudentId
},
include: [
{
model: db.WorkbookQuestion,
include: [db.Question]
}
],
limit: 10,
order: [['gradedAt', 'DESC']]
});
}).each(function(dbWorkbook) {
return Promise.resolve(dbWorkbook.WorkbookQuestions).each(function(dbWorkbookQuestion) {
var passageIndex;
passageIndex = _.findIndex(passageCounts, function(passageCount) {
return passageCount.id === dbWorkbookQuestion.Question.PassageId;
});
if (passageIndex !== -1) {
return passageCounts[passageIndex].count++;
}
});
}).then(function() {
passageCounts = _.sortBy(passageCounts, 'count');
return passageCounts;
});
};
and I want to unit test it (I think). I instrumented mocha to do the testing, but my test doesn't seem all that.. thorough:
describe('Finding the least used Passage', function() {
it('should have a function called findLeastUsedPassage', function() {
return expect(WorkbookLib.findLeastUsedPassage).to.exist;
});
return it('should return the least used passages for a student', function() {
return WorkbookLib.findLeastUsedPassage(10).then(function(passageCounts) {
var passageCountsLength;
passageCountsLength = passageCounts.length;
expect(passageCountsLength).to.equal(74);
expect(passageCounts[0].count).to.be.at.most(passageCounts[1].count);
expect(passageCounts[1].count).to.be.at.most(passageCounts[5].count);
expect(passageCounts[56].count).to.be.at.most(passageCounts[70].count);
return expect(passageCounts[70].count).to.be.at.most(passageCounts[73].count);
});
});
});
What's the right approach to unit testing something like this?
This is a great resource for understanding how to break up your code to able to test it.
Currently, you're code can't be tested well because the logic is all intermingled between multiple database calls, business logic, and glue code. What you need to do is break it all out into multiple named functions that each do one thing, like you do now. Expect that instead of creating the functions in the chain you should create them outside of the chain, then just call them in the promise chain.
var passageCounts = [];
function findAllActivePassages() {
passageCounts = [];
return db.Passage.findAll({
where: {
active: true
}
})
}
function countPassages(dbPassage) {
var passage;
passage = dbPassage.get();
passage.count = 0;
return passageCounts.push(passage);
}
function findAllSubjects(StudentId) {
return db.Workbook.findAll({
where: {
SubjectId: 1,
gradedAt: {
$ne: null
},
StudentId: StudentId
},
include: [
{
model: db.WorkbookQuestion,
include: [db.Question]
}
],
limit: 10,
order: [['gradedAt', 'DESC']]
});
})
// ...
findAllActivePassages()
.each(countPassages)
.then(function() {
return findAllSubjects(studentId)
})
// ...
Now you can test each function individually and in isolation to ensure that they do what you expect
So for starters, you probably want to break up your promise chains to make the discrete units of your code more apparent. I did some quick psuedo javascript (most familliar w/ node so apologies if this doesn't fit vanilla javascript as cleanly).
var p1 = db.Passage.findAll({ where: { active: true }})
var p2 = db.Workbook.findAll({
where: {
SubjectId: 1,
gradedAt: {
$ne: null
},
StudentId: StudentId
},
include: [
{
model: db.WorkbookQuestion,
include: [db.Question]
}
],
limit: 10,
order: [['gradedAt', 'DESC']]
});
Promise.all([p1, p2])
.then(function(results){
var passages = results[0]
var workbooks = results[1];
var passageCounts = {};
passages.foreach(function(passage){
passagecounts[passage.get().id] = 0
});
workbooks.foreach(function(workbook){
workbook.workBookQuestions.foreach(function(question){
return passageCounts[dbWorkbookQuestion.Question.PassageId] += 1;
})
});
return Promise.resolve(passageCounts)
}).then(function(passageCounts){
passageCounts = _.sortBy(passageCounts, 'count'); //this has to change but don't know what underscore offers for sorting an object used as a hashmap
return passageCounts;
});
Now as far as unit testing - you're looking to test discrete units of it so the following use cases seem reasonable:
Do I get any result back when expected?
If i give it specific values are they sorted in the way I expect?
If I have no results for either query does it break? Should it?
It may behoove you to break out the DB calls from the logic and pass the results into a method, makes testing some of the scenarios a bit easier.
What is the best approach to take when making multiple calls to an API for data needed in the same view?
For example, you have multiple select boxes which need to contain data pulled in from outside the app, all in the same view.
Is there a more elegant solution than simply firing them all at once in your controller? Such as the following
app.controller('myCtrl', function($service) {
$service.getDataOne().then(function(response) {
$scope.dataOne = response;
}, function(error) {
console.log(error);
});
$service.getDataTwo().then(function(response) {
$scope.dataTwo = response;
}, function(error) {
console.log(error);
})
});
etc...with each service function performing a $http.get request.
While this works, I feel there is probably a more elegant solution.
Any thoughts as always is much appreciated.
You can use q.all(), as it accepts an array of promises that will only be resolved when all of the promises have been resolved.
$q.all([
$service.getDataOne(),
$service.getDataTwo()
]).then(function(data){
$scope.dataOne = data[0];
$scope.dataTwo = data[1];
});
If you look at the link, q.All() is at the very bottom of the page
I believe you are looking for the $q service.
http://jsfiddle.net/Zenuka/pHEf9/21/
https://docs.angularjs.org/api/ng/service/$q
function TodoCtrl($scope, $q, $timeout) {
function createPromise(name, timeout, willSucceed) {
$scope[name] = 'Running';
var deferred = $q.defer();
$timeout(function() {
if (willSucceed) {
$scope[name] = 'Completed';
deferred.resolve(name);
} else {
$scope[name] = 'Failed';
deferred.reject(name);
}
}, timeout * 1000);
return deferred.promise;
}
// Create 5 promises
var promises = [];
var names = [];
for (var i = 1; i <= 5; i++) {
var willSucceed = true;
if (i == 2) willSucceed = false;
promises.push(createPromise('Promise' + i, i, willSucceed));
}
// Wait for all promises
$scope.Status1 = 'Waiting';
$scope.Status2 = 'Waiting';
$q.all(promises).then(
function() {
$scope.Status1 = 'Done';
},
function() {
$scope.Status1 = 'Failed';
}
).finally(function() {
$scope.Status2 = 'Done waiting';
});
}
Credit: Code shamelessly stolen from unknown creator of fiddle.
If it for loading the looku pdata for all the dropdowns, I would make one call to get all the lookup data in one single payload. Something like this. Each property value is an array of items for each dropdown.
{
"eventMethods": [
{
"name": "In Person",
"id": 1
},
{
"name": "Phone",
"id": 2
}
],
"statuses": [
{
"name": "Cancelled",
"id": 42
},
{
"name": "Complete",
"id": 41
}
]
}