I'm a newbie in javascript and node js. I actually want to compare two data based on MySQL value.
what I want to do is Loop for the pair of data -> get value from db -> concat pair of data and value -> endloop
Here's my code
routes/masterdata.js
var Masterdata = require('../models/Masterdata');
var outputFile = {}
for (var i = 0; i < dataFile.length; i++) {
if (dataFile[i]['existing'] != null) {
for (var x = 0; x < dataFile.length; x++) {
var param = {
tech_row: dataFile[i]['existing'],
tech_col: dataFile[x]['new']
};
Masterdata.compareData(param, function(err, rows) {
console.log(rows);
outputFile.push({
value: rows
});
});
}
}
}
console.log(outputFile);
models/Masterdata.js
var Masterdata = {
compareData: function(param, callback) {
return db.query('SELECT value FROM sod_matrix WHERE TECH_NAME_ROW = ? AND TECH_NAME_COL = ?', [param.tech_row, param.tech_col], callback);
}
}
My Question is how to populate data from function compare data into an array in the loop?
var Promise = require('bluebird');
var completed=[];
var Masterdata = require('../models/Masterdata');
var outputFile = []; //should be an array
for (var i = 0; i < dataFile.length; i++) {
if (dataFile[i]['existing'] != null) {
for (var x = 0; x < dataFile.length; x++) {
var param = {
tech_row: dataFile[i]['existing'],
tech_col: dataFile[x]['new']
};
completed.push(new Promise(resolve, reject){
Masterdata.compareData(param, function(err, rows) {
if(err)
{
reject(err);
}
else
{
console.log(rows);
outputFile.push(rows); //that;s pretty enough
resolve();
}
});
});
}
}
}
Promise.all(completed)
.then((res)
{
console.log(outputFile);
});
Related
A NodeJs based quiz app where the admin adds the question. Got random unique indexes for those questions, but every time the page reloads, these indexes change:
router.get('/start',ensureAuthenticated,(req,res) => {
Question.aggregate([{$group:{_id:"$Category",ques:{$push:"$$ROOT"},count:{$sum:1}}}],(err,data)=>{
Test.find({},(err,doc) => {
var username=req.user.email;
var quesarray = [];
for(var i=0; i < data.length; i++) {
for(var j=0;j<doc[0].selectcategory.length;j++) {
if(data[i]._id === doc[0].selectcategory[j]) {
var set = new Set();
while(set.size < Number(doc[0].questioncount[j])) {
var x = Math.floor(Math.random() * data[i].count);
set.add(x);
}
var a = [...set];
console.log(data[i]._id);
quesarray = [...quesarray,[...set]];
console.log(a);
}
}
}
var catg = [...doc[0].selectcategory];
var set = new UserQset({
username,
catg,
quesarray
});
set.save((err)=>{
if(!err) {
console.log("done");
}
})
res.render('newfile',{
set,
data,
doc
})
})
})
})
How do I stop the changing of indexes on page reload?
I am trying to hit an api and setting data to an object properties. I am setting few properties inside javascript promise and then pushing object in array outside the promise. So now object pushed before values returned from promise. How to solve this?
My code is here.
const getUserExchangeAccountDetails = function(props, params, callback) {
const client = new bittrex(constants.bittrexApiKey, constants.bittrexSecretKey);
let responseArray = [];
let tempArr = [];
let otherArr = [];
let coinNumber = 0;
return new Promise(function(resolve, reject) {
client.getbalances(function (err, response, taskcallback) {
if (err) {
reject(err);
} else {
let coinsList = response.result;
console.log("Results-----", response.result);
for(let i = 0; i < response.result.length; i++ ){
let coin = {
currency : "",
balance : 0,
usdPrice : 0,
coinsInUsd : [],
totalCoins : 0,
};
if(response.result[i].Currency != null ||
response.result[i].Currency != ""){
coin.currency = response.result[i].Currency;
}
if(response.result[i].Balance > 0 ){
coin.balance = response.result[i].Balance;
}
if(coin.currency != "" && coin.balance > 0){
coinNumber = coinNumber + 1;
coin.totalCoins = coinNumber;
if (coin.currency != 'BTCP') {
currenciesService.getCurrencyLatestInfo(coin.currency).then((data) => {
coin.usdPrice = data;
let usdData = conversionIntoDollar.coinsConversionInUsd(coin.balance, coin.usdPrice);
coin.coinsInUsd.push(usdData);
});
}
responseArray.push(coin);
console.log(responseArray);
}
}
resolve(responseArray);
} //else
});
})
}
Here is output of my code, values returning form promises are empty, rest of the properties are working fine.
Output Data screenshot
I am trying to use $.when apply in my code. However, it seems that the format return is different for single and multiple request. How can i cater for it?? I am trying not to have another if else outside of it.
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
This is what i do not want to do.
if (apiRequestList.length === 1) {
$.ajax({
});
} else {
$.when.apply(null, apiRequestList).then(function () {
for (var i = 0; i < arguments.length; i++) {
var value = arguments[0];
}
});
}
You can simply convert arguments into an array, when the length of apiRequestList is 1:
$.when.apply(null, apiRequestList).then(function() {
var _arguments = Array.prototype.slice.call(arguments);
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
});
Live Example on jsFiddle (since we can't do ajax on Stack Snippets):
function x(a) {
return $.post("/echo/html/", {
html: "a = " + a,
delay: Math.random()
});
}
function doIt(apiRequestList) {
$.when.apply(null, apiRequestList).then(function() {
var _arguments = arguments;
if (Array.isArray(apiRequestList) && apiRequestList.length === 1)
_arguments = [arguments];
for (var i = 0; i < _arguments.length; i++) {
var value = _arguments[i][0];
console.log(value);
}
console.log("----");
});
}
doIt([x(1), x(2), x(3)]);
doIt([x(4)]);
Example output (it'll vary because of the Math.random()):
a = 4
----
a = 1
a = 2
a = 3
----
I have a table named "circle" and it represents mailing list.
Circle can contain user id in invitedUser or circle id in invitedCircle.
I need to get all circles id that contain specific user (in the code: 1-9).
For example if studantA is in CircleA
CircleA is in CircleB
so i need to get for studantA as output CircleA and CircleB.
I try to find all circles who conect each others by while and each, but the status of the job is : Could not connect to Cloud Code.
How can I run this query until no result found?
Parse.Cloud.job("fillMemberInCircles", function (request, status) {
var studentId = "123456789";
var output = [];
var lowLayer = [];
var highLayer = [];
// Get circles when the student appears in column invitedUsers
var invitedUsers = new Parse.Query("circles");
invitedUsers.equalTo("invitedUsers", studentId);
invitedUsers.find({
success: function (invitedUsersResults) {
if (invitedUsersResults.length > 0) {
for (var i = 0; i < invitedUsersResults.length; i++) {
output.push(invitedUsersResults[i].id);
lowLayer.push(invitedUsersResults[i].id);
}
var counter = lowLayer.length;
var _ = require('underscore.js');
while (counter > 0) {
//var _ = require('underscore.js');
_.each(lowLayer, function (currCircle) {
var invitedCirclesQuery = new Parse.Query("circles");
invitedCirclesQuery.equalTo("invitedCircles", currCircle);
invitedCirclesQuery.find().then(function (results) {
if (results.length != 0) { // item exists
for (var j = 0; j < results.length; j++) {
if (output.indexOf(results[j].id) == -1) {
output.push(results[j].id);
highLayer.push(results[j].id);
}
}
}
}).then(function () {
counter--;
if (counter == 0) {
if (highLayer.length == 0) {
console.log("OK");
lowLayer = [];
status.success("SUCSESS: " + output.length.toString());
} else {
lowLayer = highLayer;
counter = lowLayer.length;
highLayer = [];
}
}
});
});
}
}
//status.success("SUCSESS: " + output.length.toString());
},
error: function () {
status.error("[fillMemberInCircles] There was some error with queryMajors");
}
});
});
SaveData.js
function queryDB(callback) {
var sqlTxt = "SELECT * FROM DEMO";
db.transaction(
function(tx) {
tx.executeSql(sqlTxt, [],
function(tx, results) {
var item_Codes = [];
for (var i = 0; i < results.rows.length; i++) {
item_Codes.push({item_code: results.rows.item(i).itemCode});
}
callback(item_Codes);
})
, errorCB;
});
return false;
}
main.js
queryDB();
console.log( item_Codes);
I have above two methods to retrieve data from database .It works fine but i need to combine these two methods to one method and return the itemCodes array.
var processResult = function(items)
{
//process returned array 'items'
}
function queryDB(callback) {
var sqlTxt = "SELECT * FROM DEMO";
db.transaction(
function(tx) {
tx.executeSql(sqlTxt, [],
function (tx, results) {
var item_Codes = [];
for (var i = 0; i < results.rows.length; i++) {
item_Codes.push({item_code: results.rows.item(i).itemCode});
}
callback(item_Codes);
})
, errorCB);
});
return false;
}
and call it with:
queryDB(processResult);
or you can use global variable item_Codes instead of function processResult