getting values from sqlite database and insert into a array - javascript

I've made a function myFunction which performs simple task i.e. to retrieve data from sqlite database and save it in a array which can be used easily. This function should follow these steps to fulfill my functionality.
To retrieve data from database.
To save it into array.
return array
But it is performing these steps in this sequences; 3, 1, 2, so I am not getting the data because it returns without getting it.
e.g.
function myFunction() {
var ret;
var arr = [];
db.transaction(function (trans) {
trans.executeSql('SELECT * FROM tblname', [],
function (transaction, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
ret = row.urlcolmn;
arr.push(ret);
alert('alert 1'); // just to check which line(alert) is called first
}
}
}, errorHandler);
}, errorHandler, nullHandler);
alert('alert 2'); // just to check which line(alert) is called first
return arr;
}
In above code alert 2 is shown before alert 1..... that's why it doesn't return value in array. This problem can be because sqlite in JS is Asynchronous.

Related

How to use caching with the riot-lol-api npm package?

QUESTION:
After reading this:
https://www.npmjs.com/package/riot-lol-api#caching
I am still confused. This is my first time trying to cache api responses.
For example, I do not know what values are available for YOUR_CACHE_STRATEGY and it is not explained in the docs.
Essentially, I would be looking for an example, like how can I cache and serve for 5 min the response from /lol/summoner/v3/summoners/by-name/ ?
CODE:
riotRequest.request(region.toLowerCase(), 'summoner', '/lol/summoner/v3/summoners/by-name/'+encodeURI(player), function(err, data) {
if (!err) {
var summonerID = data.id;
} else {
console.error("ERROR1: "+err);
res.render("page", {errorMessage: "Player not found !"});
}
});
The documentation is not very detailed indeed. What you need to do is basically implement the cache object as specified in the code sample from the doc (the commented area).
Below is an example of caching to an array (in memory). You could also save this array to a file or into a Redis database as suggested in the doc.
//cacheData holds objects of type {key: 123, value: "request data"}
var cacheData = []
var cacheIndex = 0
function deleteFromCache(key) {
for (var i = 0; i < cacheData.length; i++) {
if (cacheData[i].key == key) {
cacheData.splice(i, 1);
return;
}
}
}
var cache = {
get: function(region, endpoint, cb) {
for (var entry of cacheData) {
if (entry.value == data) {
//we have a cache hit
return cb(null, entry.value);
}
}
return cb(null, null);
},
set: function(region, endpoint, cacheStrategy, data) {
var key = cacheIndex++;
var value = data;
cacheData.push({key, value});
//cacheStrategy is a number representing the number of seconds to keep the data in cache
setTimeout(() => {
deleteFromCache(key);
}, cacheStrategy * 1000);
}
};
YOUR_CACHE_STRATEGY is an object that is passed to your set function in the cacheStrategy parameter. They suggest it can be a number representing the lifespan of the cache entry, so I implemented a timer to delete the cache entry after a number of seconds equal to cacheStrategy.
You would call the request using this number:
riotRequest.request(region.toLowerCase(), 'summoner', '/lol/summoner/v3/summoners/by-name/'+encodeURI(player), 30, function(err, data) {//.....
To enable caching you need to pass the cache object to the constructor of RiotRequest :
var riotRequest = new RiotRequest('my_api_key', cache);

CRM Javascript Automatically Populated a Look-up Value with a specific field

I'm trying to write a javascript on CRM Phone Call page. We have a custom look-up field called new_department, and we want to automatically populate the field with value "IT" (there should be one) when the form is opened.
The thing is we have a separate Dev and Production CRM link therefore I cannot just assign a hard-coded GUID value into this field. So first I wrote a Rest Retrieve Multiple to get the correct department.
Then my problem is I'm not sure about the result returned from this Retrieve Multiple. How do I grab just the GUID from Rest? I'm seeing that this is a type of {Object}. Then lastly how do I go about setting the lookup value after retrieving the {Object}? Any help is greatly appreciated.
Here is my code.
function phonecall() {
var formType = Xrm.Page.ui.getFormType();
if (formType == 1) //create
{
//RetrieveMultiple function
var DepartmentId = getITDepartment();
//set the lookup value
var ID = DepartmentId.id;
var departmentValue = new Array();
departmentValue[0] = new Object();
departmentValue[0].id = DepartmentId;
departmentValue[0].name = 'IT';
userValue[0].entityType = "new_department";
Xrm.Page.getAttribute("new_department").setValue(departmentValue);
}
}
function getITDepartment()
{
XrmServiceToolkit.Rest.RetrieveMultiple("new_departmentSet", "$select=new_departmentId&$filter=new_name eq 'IT'",
function (results) {
if (results.length > 0)
resultList = results;
}, function (error) { alert(error); }, function onComplete() { }, false);
return resultList;
}
Thanks much.
I'm not familiar with XrmServiceToolkit but here how code could look like to work properly - I replaced only assigning part:
var DepartmentId = getITDepartment();
if (DepartmentId != null && DepartmentId.length > 0){
Xrm.Page.getAttribute("new_department").setValue([{
id: DepartmentId[0].new_departmentId,
name: "IT",
entityType: "new_department"
}]);
}
You are setting the lookup value correctly, you just need to get the Id correctly. The results variable is an array of new_department records, so try something like this:
var resultId = null;
XrmServiceToolkit.Rest.RetrieveMultiple("new_departmentSet", "$select=new_departmentId&$filter=new_name eq 'IT'",
function (results) {
if (results.length > 0)
resultId = results[0].new_departmentId; //gets the first record's Id
}, function (error) { alert(error); }, function onComplete() { }, false);
return resultId;

Add sqlite query result to angularjs $scope

I have this sqlite query in a angularjs app.
$scope.testArr = [];
$scope.testFunk = function(){
var db = window.openDatabase("test", "1.0", "Test DB", 1000000);
db.transaction(function(tx){
tx.executeSql('SELECT * FROM EVENTS',
[],
//Callback function with transaction and
//results objects
function(tx, results){
//Count the results rows
var rowsCount = results.rows.length;
//Loop the rows
for (var i = 0; i < rowsCount; i++){
//Build a results string, notice the
//column names are called
$scope.testArr.push({
id: results.rows.item(i).eventId,
nameSel: results.rows.item(i).eventNameSel,
name: results.rows.item(i).eventName,
eventDesc: results.rows.item(i).eventDesc,
eventUrl: results.rows.item(i).eventUrl,
time: results.rows.item(i).eventTime
})
}
console.log($scope.testArr);
},
errorHandler);
});
}
//
The console.log returns the right objects, but If I do a console.log outside of the db.transaction function it returns empty. The problem is that I want to call the $scope.testFunk() function and return the result from the query to a variable which I then can process further, like:
var result = $scope.testFunk();
console.log(result);
// prints results from query.
I suggest you to use a service.
The reason it's not working now is because when you trying to print the results, it's still not populated. you can add $watch over results and work with it when it's populated.
$scope.testFunk(); // modify $scope.results within the function
$scope.$watch('results', function(resultsNewVal, resultsOldVal) {
console.log(resultsNewVal);
}

How To handle result set of websql in html 5?

I m creating mobile web application using html5 and javascript.I m having two javascript files. AttributesDatabase.js and AttributeView.js.From AttributeView.js i m calling one function from AttributeDatabase.js in that i m executing one select query.Now the query result should go to AtttributeView.js.But the Websql transaction is asynchronous call that is what it is not returning proper result.Is there any way to handle the websql result.
Please help if any way there?
Edited
AttributeView.js
var AttributeDAOObj = new AttributeDAO();
AttributeDAOObj.GetAttributeList();
alert(AttributeDAOObj.GetAttributeList()); //This alert is coming as undefined.
AttributeDAO.js
this.GetAttributeList = function () {
var baseDAOObj = new BaseDAO();
var query = "SELECT AttributeName FROM LOGS";
// this.Successcalbackfromsrc = this.myInstance.Successcalback;
var parm = { 'query': query, 'Successcalback': this.myInstance.Successcalback };
baseDAOObj.executeSql(parm);
}
//To Create database and execute sql queries.
function BaseDAO() {
this.myInstance = this;
//Creating database
this.GetMobileWebDB = function () {
if (dbName == null) {
var dbName = 'ABC';
}
var objMobileWebDB = window.openDatabase(dbName, "1.0", dbName, 5 * 1024 * 1024);
return objMobileWebDB;
}
//Executing queries and getting result
this.executeSql = function (query) {
var objMobileWebDB = this.myInstance.GetMobileWebDB();
objMobileWebDB.transaction(function (transaction) {
//In this transaction i m returning the result.The result value is coming.
transaction.executeSql(query, [], function (transaction, result) { return result; }, this.Errorclback);
});
}
}
The problem is in you succes call back (like in the comment to your question, stated by DCoder)
function (transaction, result) { return result; }
this is returning where to?
So this is how to do it (or at least one way)
you can do for example:
function (transaction,result){
console.log("yes, I have some result, but this doesn't say anything, empty result gives also a result");
// so check if there is a result:
if (result != null && result.rows != null) {
if (result.rows.length == 0) {
// do something if there is no result
}else{
for ( var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
var id = result.rows.item(i).id; //supposing there is an id in your result
console.log('Yeah! row id = '+id);
}
}
}else{
// do something if there is no result
}
};
note the code above can be compacter, but this is how to understand it better.
another way is to put this function is a seperate piece of code, so you keep the sql statement more compact and readable. Like you call you error callback this can be in your function (with this. in front of it) or a completely seperate function.

Accessing variable inside WebSQL Function

I am using the following code
var Year12=new Array();
GetYear(function(Year12)
{
alert(Year12);
});
function GetYear(callback)
{
var selectAllStatement = "SELECT DISTINCT year FROM mytable";
var db = openDatabase("Postit", "1.0", "Notebook", 200000);
var dataset;
alert("1");
db.transaction(function(tx) {
alert("2");
tx.executeSql(selectAllStatement, [], function(tx, result)
{
alert("3");
dataset = result.rows;
for (var i = 0, item = null; i < dataset.length; i++)
{
item = dataset.item(i);
Year12[i]=item['year'];
}
callback(Year12);
});
});
}
Here the tx.executeSql statements are not getting executed means alert 3 is not displaying.Is there any way to do this
The db.transaction and tx.executeSql calls are asynchronous, hence the callback functions. That means that GetYear will finish executing and return before the tx.executeSql callback will populate your Year12 array.
Once you have asynchronous behavior and callbacks, the only sensible solution is, of course, more callbacks. You need a structure more like this:
function GetYear(callback) {
//...
db.transaction(function(tx) {
//...
tx.executeSql(selectuniqueyearStatement, [], function(tx, result) {
var Year12 = [ ];
//... populate the locale Year12 using result.rows
callback(Year12);
});
});
}
and then use it like this:
GetYear(function(year12) {
// Do whatever you need to do with the year12 array...
});
Basically the same code structure and strategies that you use with AJAX calls.

Categories