How to retrieve an array of data arrMyLatLng function - javascript

How to retrieve an array of data arrMyLatLng function.
db.transaction(queryDB, errorCB);
function queryDB(tx)
{
tx.executeSql('SELECT * FROM Attractions', [], querySuccess, errorCB);
}
function querySuccess(tx, results)
{
var arrMyLatLng = [];
var len = results.rows.length;
var arrLatitude=[], arrLongitude=[];
for (var i=0; i<len; i++)
{
arrLatitude[i] = results.rows.item(i).latitude;
arrLongitude[i] = results.rows.item(i).longitude;
arrMyLatLng[i] = new google.maps.LatLng(arrLatitude[i], arrLongitude[i]);
}
return arrMyLatLng ; // Need this array to manipulate the data from it is outside of the function.
}
Thanks

You're performing an asynchronous operation which will execute its callback whenever the operation completes. Hence there is nothing that you can return arrMyLatLng to. All work with arrMyLatLng will need to be done in the callback. One thing you can do is call another function from querySuccess and pass arrMyLatLng to it:
function querySuccess(tx, results) {
var arrMyLatLng = [];
var len = results.rows.length;
var arrLatitude=[], arrLongitude=[];
for (var i=0; i<len; i++) {
arrLatitude[i] = results.rows.item(i).latitude;
arrLongitude[i] = results.rows.item(i).longitude;
arrMyLatLng[i] = new google.maps.LatLng(arrLatitude[i], arrLongitude[i]);
}
someOtherFunction(arrMyLatLng);
}

Related

Wait for nested async calls to finish

I have a series of nested async calls that need to finish before my code continues. Function save_part1 calls the sqlite database and returns the rows of interest. For each of those rows, I make an ajax call to a save them remotely.
From what I have read about promises and deferred, I have only seen them being used in the context of ajax calls. And on top of that, it makes my brain hurt.
Question: how do I wait until all the ajax calls have completed before starting save_part2?
function save()
{
save_part1();
//this should only happen after all the ajax calls from save_part1 are complete
save_part2();
}
function save_part1()
{
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM TABLE1", [],
function (transaction, results) {
for (var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
ajaxCall_item1(row);
}
}, errorHandler)
});
}
function save_part2()
{
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM TABLE2", [],
function (transaction, results) {
for (var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
ajaxCall_item2(row);
}
}, errorHandler)
});
}
As long as you have ajaxCall_item returning the jQuery deferred object, you can have save_part1 return a deferred object, collect the returned promises into an array, call them with $.when and resolve the "promise" once all of the requests have completed. Then you will be able to write: save_part1().then(save_part2);. Here is an untested example:
function save() {
save_part1().then(save_part2).fail(function(err) {
// ohno
});
}
function ajaxCall_item1(row) {
return $.ajax({ ... });
}
function save_part1()
{
var dfd = jQuery.Deferred();
var promises = [];
db.transaction(function (tx) {
tx.executeSql("SELECT * FROM TABLE1", [],
function (transaction, results) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
promises.push(ajaxCall_item1(row));
}
$.when.apply($, promises).then(function() {
dfd.resolve.apply(dfd, arguments);
});
}, function(err) {
dfd.reject(err);
});
});
return dfd;
}

callbacks when trying to create an array from asynchronous calls in javascript

I am trying to create an array from an asynchronous get request using a function that uses a for loop in order to pass a parameter in the get request.
var loadRarity = function () {
var rarities = [];
for (var i =0; i < deck.length; i++) {
Card.get({cardName: deck[i].card_name}, function(data) {
rarities.push(data.data[0].rarity);
console.log(rarities); //20 instances where the array is being populated
});
console.log(rarities);// result :20x [] empty array
}
return rarities;
};
var raritiesArray = loadRarity();
console.log(raritiesArray); //empty array
I can't figure out how to use the callback to make this work.
An option is to increment a counter to check if you are on the last callback an then do any needed operation in that last callback
var loadRarity = function () {
var rarities = [];
var counter = 0; // initialize counter
for (var i =0; i < deck.length; i++) {
Card.get({cardName: deck[i].card_name}, function(data) {
counter += 1; //increment counter
rarities.push(data.data[0].rarity);
console.log(rarities); //20 instances where the array is being populated
if(counter == deck.length){ //if true you are in the last callback
console.log(raritiesArray); // array with all the elements
}
});
}
return rarities;
};
var raritiesArray = loadRarity();
Waiting for all this async stuff to happen, your code that needs to use the result should be in its own callback, which runs when the result is available. For example:
var loadRarity = function(cb) {
var rarities = [],
counter = 0,
done = function(){
if(counter++ === deck.length - 1){
cb(rarities);
}
};
for (var i =0; i < deck.length; i++) {
Card.get({cardName: deck[i].card_name}, function(data) {
rarities.push(data.data[0].rarity);
done();
});
}
};
loadRarity(function(completedRarities){
console.log(completedRarities);
});
Sample (using an image onload fn to simulate your asysnc call): http://codepen.io/RwwL/pen/VeeEBR?editors=001

javascript - OOP - executeSql return the result into a var , it shows undefined

I'm trying to use Phonegap function executeSql to fetch a SQL Query with a select statement , i'm just want to return a query results from my OOP function
i read this question
Return executeSQL function
but i can't undrestand it well so i can't apply it on my code
function Invoice() {
this.read = function(){
var stmnt = "SELECT * FROM invoices ORDER BY ID DESC";
function callback(callback_fun){
var myrows = [];
db.transaction(function(tx){
tx.executeSql(stmnt, [], function(tx,result){
for(var i = 0; i < result.rows.length; i++){
var row = result.rows.item(i);
myrows.push(row);
}
//console.log(myrows);
callback_fun(myrows);
}, function(tx,error){
alert('Error: '+error.message);
return;
});
});
}
callback(function(newResult){
return newResult;
});
};
};
var newInvoice = new Invoice();
var myResult = newInvoice.read();
alert(myResult);
You need to set your callback() plus callback_fun() as an return value like this:
function Invoice() {
this.read = function(){
var stmnt = "SELECT * FROM invoices ORDER BY ID DESC";
function callback(callback_fun){
var myrows = [];
db.transaction(function(tx){
tx.executeSql(stmnt, [], function(tx,result){
for(var i = 0; i < result.rows.length; i++){
var row = result.rows.item(i);
myrows.push(row);
}
//console.log(myrows);
return callback_fun(myrows); // <<----- RETURN
}, function(tx,error){
alert('Error: '+error.message);
return;
});
});
}
return callback(function(newResult){ // <<<<<<<<----------- RETURN
return newResult;
});
};
};
What Javascript Callstack looks like:
you are calling Invoice.read(), but read-Function has no return keyword so it doesn't return anything, what leads to undefined
You are calling your callback function. Which also returns nothing.
EDIT2:
Oh ok you are invoking another function db.transaction which currently returns the value to your callback function. So you could probably do that:
function callback(callback_fun){
var myrows = [];
return db.transaction(function(tx){
tx.executeSql(stmnt, [], function(tx,result){
for(var i = 0; i < result.rows.length; i++){
var row = result.rows.item(i);
myrows.push(row);
}
//console.log(myrows);
return callback_fun(myrows); // <<----- RETURN
}, function(tx,error){
alert('Error: '+error.message);
return;
});
});
}
EDIT:
This is your code. Oh Well a little bit simplified: JSBIN
This is my code. JSBIN-Working Example
You need to press Run with JS in the right corner.

Function not returning value synchronously

I have the following condition where syncAnalytics is called first. Inside this function, there is another function, retreiveAnalyticsData, written to retrieve the locally stored data.
But before the value is returned from retreiveAnalyticsData, the rest of function syncAnalytics gets executed.
DemoModule.factory('ApplicationAnalytics', function ($http, $location, DBO) {
return {
syncAnalytics: function () {
console.log("syncAnalytics called");// Getting displayed 1st
// Retrieve analytics data available data from db
var inputData = this.retreiveAnalyticsData();
console.log("Input Data : " + JSON.stringify(inputData)); // Getting displayed 4th
},
retreiveAnalyticsData: function () {
console.log('retreiveAnalyticsData called');// Getting displayed 2nd
// Select all rows from app_analytics table in db
var selectQuery = "SELECT * FROM app_analytics";
var analyticsData = [];
DBO.execQry(selectQuery, function (results) {
var len = results.rows.length,
i;
for (i = 0; i < len; i++) {
analyticsData.push(results.rows.item(i).text);
}
console.log(analyticsData); //Getting displayed 5th
return analyticsData;
});
console.log('retreiveAnalyticsData ended');// Getting displayed 3rd
}
};
});
So basically :
var inputData = this.retreiveAnalyticsData(); //This should be executed before the below line.
console.log("Input Data : " + JSON.stringify(inputData)); // Getting displayed 4th
Any insight will be greatly appreciated.
Note : I am using AngularJS
DBO.execQry is an asynchronous function. You may see this because of the callback pattern - e.g. the second paramter of execQry is a function that is called if execQry is ready retrieving the data. I guess what you see is, that console.log('retreiveAnalyticsData ended'); is printed out before console.log(analyticsData);
How to handle this?
1) The oldschool way would be using a callback function:
syncAnalytics: function () {
this.retreiveAnalyticsData(function(inputData){
console.log("Input Data : " + JSON.stringify(inputData));
});
},
retreiveAnalyticsData: function (callback) {
var selectQuery = "SELECT * FROM app_analytics";
var analyticsData = [];
DBO.execQry(selectQuery, function (results) {
var len = results.rows.length,
for (var i = 0; i < len; i++) {
analyticsData.push(results.rows.item(i).text);
}
callback(analyticsData);
});
}
But this way has a lot of disadvantages. What if you would like to handle erros or need to to make multiple asynchronous calls or sync them together? So we came to the promise pattern.
2) The Promise Pattern by $q
syncAnalytics: function () {
this.retreiveAnalyticsData().then(function(inputData){
console.log("Input Data : " + JSON.stringify(inputData));
});
},
retreiveAnalyticsData: function () {
var selectQuery = "SELECT * FROM app_analytics";
var analyticsData = [];
var deferred = $q.defer();
DBO.execQry(selectQuery, function (results) {
var len = results.rows.length,
for (var i = 0; i < len; i++) {
analyticsData.push(results.rows.item(i).text);
}
deferred.resolve(analyticsData);
});
return deferred.promise;
}

combine two javascript methods together

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

Categories

Resources