YDN-DB with multiple deferred - javascript

Im trying to use multiple deferred with jquery $.when but so far no luck, this is my code:
var req = $.when(db.count('items'),db.values('items'),db.get('config', 1));
req.done(function(count,r,config) {
var currency = config.currency;
if(count > 0){
var n = r.length;
for (var i = 0; i < n; i++) {
var id = r[i].id;
var itemId = r[i].itemId;
console.log('ID: '+id+' itemID: '+itemId+' Currency: '+currency);
}
}
});
My sample isn't working so hope you guys can help me, I searched everywhere for a solution. Thanks

I see. I will see how I could implement jquery deferred list. Although ydn-db promise has done, fail and them, etc, it is not $.Deferred instance. An adaptor approach is require.
Currently, use transaction as follow:
var results = {};
var tx_req = db.run(function(tx_db) {
tx_db.count('items').done(function(x) {
results.count = x;
});
tx_db.values('items').done(function(x) {
results.values = x;
});
tx_db.get('config', 1).done(function(x) {
results.config = x;
});
}, ['items', 'config'], 'readonly');
req.done(function() {
var count = results.count;
var r = results.values;
var config = results.config;
var currency = config.currency;
if(count > 0){
var n = r.length;
for (var i = 0; i < n; i++) {
var id = r[i].id;
var itemId = r[i].itemId;
console.log('ID: '+id+' itemID: '+itemId+' Currency: '+currency);
}
}
results = null;
});
It is a bit messy, but more efficient because all three query run in a single transaction.
EDIT:
Just need to add promise() method that return an object having done, fail and progress functions. Should be doable without much overhead. Basically you can do an adaptor like:
var wrap = function(req) {
req.promise = function() {
return req; // Note: req has done, fail and progress functions.
// however, jquery api demand promise to return a new deferred.
}
return req;
}
$.when(wrap(db.count('items')),wrap(db.values('items')),wrap(db.get('config', 1)));
Here is complete code in jsfiddle.
EDIT:
From release 0.8.1, promise method is added to request object and wrapping is no longer needed. Example.

Related

How to track changes to the model for the ui-scroll

Specifically for javascipt
I dont know how to do it.
I have $scope.models , that I deduce the screen.
Method get: give me array-data from server
$scope.models = {
get: function (index, count, success)
{
filterModel.Enddt = $scope.filter.enddt.toISOString();
filterModel.Startdt = $scope.filter.startdt.toISOString();
filterModel.Take = $scope.filter.nodeCount.count;
filterModel.Type = $scope.filter.chooseView.value;
filterService.getElectricityData(filterModel).then(function (data) {
var results = [];
var start = Math.max(0, index);
var end = Math.min(index + count, data.length);
for (var i = start; i < end; i++) {
results.push(data[i]);
}
success(results);
});
}
};
I think so to need create method reload() or revision(), that is deprecated.
Don't send me documentation from github, that is for coffee script.
And don't send me converter coffee to js:)
Please help me :C

Parse.com - Getting 400 Bad Request, Using Inner Queries

I am performing multi-level inner queries but it gives me a 400 Bad Request for the line with the find() function, what have I done wrong?
var EducationVenue = Parse.Object.extend("EducationVenue");
var EducationVenueRoom = Parse.Object.extend("EducationVenueRoom");
var EducationLessonSet = Parse.Object.extend("EducationLessonSet");
var EducationLesson = Parse.Object.extend("EducationLesson");
var eduLessonSetQuery = new Parse.Query(EducationLessonSet);
eduLessonSetQuery.matchesQuery("educationListingId", eduListingQuery);
var eduLessonQuery = new Parse.Query(EducationLesson);
eduLessonQuery.matchesQuery("educationLessonSetId", eduLessonSetQuery);
eduLessonQuery.include('educationVenueRoomId.educationVenueId');
$scope.coursesAtLocations = [];
eduLessonQuery.find({
success: function(coursesAtLocations) {
for (var i = 0; i < coursesAtLocations.length; i++) {
$scope.coursesAtLocations.push(coursesAtLocations[i]);
console.log('c at loc' + coursesAtLocations[i]);
}
}
});
The reason for this is "query has too many nested queries", what is the more convenient workaround for this?

Variable from for loop always returns 0

I am reasonably new to node.js / sails.js and have run into a problem that I know the answer is simple but I cannot seem to work it out.
My code is as follows
SendCompleted : function(req,res)
{
var updated = 0;
var params = req.params.all();
var dt = JSON.parse(decodeURI(params.id));
var connection = new sql.Connection(testrmis, function (err)
{
if (err) {
}
for(var i = 0; i < dt.length; i++) {
var obj = dt[i];
var request = new sql.Request(connection);
request.stream = true;
request.input('branchid', sql.Int(), obj.branch_id);
request.input('picklistid', sql.Int(), obj.picklist_id);
request.input('scanned',sql.Int(),obj.scanned);
request.input('expected', sql.Int(),obj.expected);
request.input('poscode', sql.VarChar(),obj.poscode);
request.input('label', sql.VarChar(), obj.label);
request.input('dt', sql.VarChar(), obj.dt);
request.execute('WAREHOUSE_InsertPiPackData');
request.on('done', function(returnValue) {
updated = updated + returnValue;
console.log(updated);
});
}
res.send("[{\"ReturnValue\":" + updated + "}]");
});
}
I am sending in 4 lines of results and my console.log(updated) counts up as it should for each line, e.g 1,2,3,4
However the res.send result for updated is always 0.
Could anyone please explain why this is happening? My var updated is outside of my loop and this is getting updated correctly, however when the loop is finished it seems to get reset to 0?
returnValue == ##rowcount from the stored procedure
request is async so
res.send("[{\"ReturnValue\":" + updated + "}]");
gets executed even before you get the callback on request as JS doesn't wait for the callback and executes the next line. What you can do is use a counter and place your res.send inside for loop.
SendCompleted : function(req,res)
{
var updated = 0;
var params = req.params.all();
var dt = JSON.parse(decodeURI(params.id));
var connection = new sql.Connection(testrmis, function (err)
{
if (err) {
}
var count = dt.length;
for(var i = 0; i < dt.length; i++) {
var obj = dt[i];
var request = new sql.Request(connection);
request.stream = true;
request.input('branchid', sql.Int(), obj.branch_id);
request.input('picklistid', sql.Int(), obj.picklist_id);
request.input('scanned',sql.Int(),obj.scanned);
request.input('expected', sql.Int(),obj.expected);
request.input('poscode', sql.VarChar(),obj.poscode);
request.input('label', sql.VarChar(), obj.label);
request.input('dt', sql.VarChar(), obj.dt);
request.execute('WAREHOUSE_InsertPiPackData');
request.on('done', function(returnValue) {
count--;
updated = updated + returnValue;
console.log(updated);
if(count == 0) res.send("[{\"ReturnValue\":" + updated + "}]");
});
}
});
}
Try for this:
May be Async problem:
for(var i = 0; i < dt.length; i++) {
//Your logic
if(i=== dt.length){
res.send("[{\"ReturnValue\":" + updated + "}]");
}
}
This is because at the time you do request.send, the value of updated is not incremented. This is because request.execute is asynchronous and done handler will be invoked after the res.send has been executed.
I would recommend a promise library (example, q). You can combine the promises and then use Q.all to do req.send when all the promises are done.
See more details here

How to solve my http request issue?

I have a question about the http request.
Here is my old post.
How to get the multiple http request results in my example?
I have modified my codes a bit. Basically I need to make multiple http requests and store them into an productGroup array. However, I am getting undefined for the returned result.
var buildProduct = function(product) {
var productGroup = [];
for(var i = 0; i < product.length; i++) {
var t = buildProductDetail(product, i)
productGroup.push(t);
}
console.log(productGroup) // I am getting undefined here.
return productGroup;
}
var buildProductDetail = function(product, i) {
var plan = {}
getProductDetail(product[i].id)
.then(function(data){
plan = {detail: data.detail, name:product[i].name}
console.log(plan) //has data
return plan;
})
}
var getProductDetail = function(id) {
return $http.get('/api/project/getProduct' + id);
}
You had undefined because your buildProductDetail function didn't return anything.
If you want a clean result use the $q api to resolve several promises at the same time.
https://docs.angularjs.org/api/ng/service/$q
I think it should work with something looking like this but I can't test without a plunkr.
Inject $q (native in angularjs, no external dep needed) and then :
var buildProduct = function(product) {
var productGroup = [];
for(var i = 0; i < product.length; i++) {
var t = buildProductDetail(product, i)
productGroup.push(t);
}
return $q.all( productGroup );
}
var buildProductDetail = function(product, i) {
var plan = {}
return getProductDetail(product[i].id) // don't forget the return there
.then(function(data){
plan = {detail: data.detail, name:product[i].name}
console.log(plan) //has data
return plan;
})
}

Javascript array results returning undefined

I have been working on a simple math game and am having problems getting the overall answer results to return after the end of the game.
Here is what my return function looks like
function pShowResults() {
var pNumResults = document.getElementById("results");
for (var i = 0; i <= 10; i++) {
pNumStore.push(pNumGuess[i]);
var pNumTable = document.createElement("div");
pNumTable.innerHTML = (pNumGuess[i]);
pNumResults.appendChild(pNumTable);
}
}
Here is the full script
Pretty much need debugging help. I new to this so I'm guessing there is a ton that's off, but as long as I can get the results fed back I should be fine.
You are not passing the value of x in many placess
$(document).ready(function () {
//declare arrays and variables for use below
var pNum1 = [];
var pNum2 = [];
var pNumAns = [];
var pNumGuess = [];
var pNumStore = [];
var pNumCarry = 0;
var pNumTrack = 0;
var pNumMessageRight = ['Awesome Job!', 'Correct!', 'Great Job!'];
var pNumMessageWrong = ['Oh No! That Was Wrong!', 'Incorrect!', 'That\'s Wrong'];
$(".Play").click(function () {
$("#popup").attr("class", "on");
pNumTrack = 0;
pNumGen(pNumTrack);
});
$(".pNumSubmit").click(function () {
pNumCalc(pNumTrack-1);
});
$(".pNumNext").click(function () {
pNumGen(pNumTrack);
});
function pNumGen(x) {
pNum1[x] = (Math.round(Math.random() * 51));
pNum2[x] = (Math.round(Math.random() * 51));
pNumAns[x] = pNum1[x] + pNum2[x];
$(".pNum1").html(pNum1[x]);
$(".pNum2").html(pNum2[x]);
$(".pNumGuess").val("");
$(".pNum1").html(pNumTrack[x]);
if (pNumTrack == 2) {
$(".pNumNext").html("");
$(".pNumSubmit").html("Close");
pShowResults();
}
pNumTrack++;
}
function pNumCalc(x) {
pNumGuess[x] = $(".pNumGuess").val();
if (pNumGuess[x] == pNumAns[x]) {
$(".message").html(pNumMessageRight[Math.floor(Math.random() * pNumMessageRight.length)]);
$(".pNumNext").html("Next Question >")
} else {
$(".message").html(pNumMessageWrong[Math.floor(Math.random() * pNumMessageWrong.length)]);
$(".pNumNext").html("Maybe The Next Question >")
}
}
function pShowResults() {
var pNumResults = document.getElementById("results");
for (var i = 0; i < pNumGuess.length; i++) {
pNumStore.push(pNumGuess[i]);
var pNumTable = document.createElement("div");
pNumTable.innerHTML = (pNumGuess[i]);
pNumResults.appendChild(pNumTable);
}
}
});
Demo: Fiddle
There is a function called pNumCalc in your code which you have set to take in an argument, but you never pass one in. You use the argument to store the results in the pNumGuess array, but since the argument is never passed in, the guesses are never stored, and you end up with undefined as the answers the user gave.
Updated fiddle: http://jsfiddle.net/dwdX9/2/. Not sure how close this is to what you actually want though, but hopefully it gets you on the right track.
Because StackOverflow wants code to to be included when JSFiddle is...:
pNumCalc(pNumTrack)
You forget to define array before use it.
function pShowResults() {
var pNumStore = new Array();
var pNumResults = document.getElementById("results");
for (var i = 0; i <= 10; i++) {
pNumStore.push(pNumGuess[i]);
var pNumTable = document.createElement("div");
pNumTable.innerHTML = (pNumGuess[i]);
pNumResults.appendChild(pNumTable);
}
}
I must suggest you should use jquery instead.
After visiting your Fiddle seems like there are many problems with the code. and also your question is unclear.
for e.g.
$(".pNumSubmit").click(function () {
//why x value not passed?
pNumCalc();
});
function pNumCalc(x) {
pNumGuess[x] = $(".pNumGuess").val();
if (pNumGuess[x] == pNumAns[x]) {
$(".message").html(pNumMessageRight[Math.floor(Math.random() * pNumMessageRight.length)]);
$(".pNumNext").html("Next Question >")
} else {
$(".message").html(pNumMessageWrong[Math.floor(Math.random() * pNumMessageWrong.length)]);
$(".pNumNext").html("Maybe The Next Question >")
}
}
Please clear which array is returning undefined so that others can help you.

Categories