Handling multiple records in Web Sql by recursive method

Posted By : Avilash Choudhary | 22-Jun-2015

Building phonegap application everyone needs to  maintain database records locally to make response fast and not make call to server every time and then synch with server after some interval to have latest and upto date data on your local database. Most of us use WebSql database to store data locally. To check how websql works you can check my previous blog here

Anyone might face problem when removing multiple records from database by making queries in loop, In that case you don’t know when all records will get removed. To solve this issue We can make recursive methods to remove multiple records so that you know when all records gets removed and do some code after that.

 

Mostly we used to write code like this:

 db.removeUserCardsData = function(data, _callback) {
	var milestoneDB = db.openDB();
		_.each(data, function(item) {
// _.each is a underscore.js loop function			
milestoneDB.transaction(function(transaction) {
				transaction.executeSql('DELETE FROM USERHOMECARDSDATA WHERE ID=?', [item], function(transaction, results) {
					// success
					//console.log("removed card data");
				}, function(e) {
					//console.log("some error removing card data");
				});
			});
		});
		_callback();
}; 
 

 

In above method callback will be fired when loop finishes but at that time some of the records might not be deleted if you have large list of items to be deleted.

To solve this we need to write recursive method

	var milestoneDB = db.openDB();
	var deleteCard = function(item, _callback) {
		milestoneDB.transaction(function(transaction) {
			transaction.executeSql('DELETE FROM USERHOMECARDSDATA WHERE ID=?', [item], function(transaction, results) {
				_callback();
				//console.log("removed card data");
			}, function(e) {
				_callback();
				//console.log("some error removing card data");
			});
		});
	};
	if (data && data.length) {
		var arrIndex = data.length - 1;
		var processRemovedCard = function(item) {
			deleteCard(item, function() {
				if (arrIndex > 0) {
					arrIndex = arrIndex - 1;
					processRemovedCard(data[arrIndex]);
				} else {
					_successCallback();
				}
			});
		};
		processRemovedCard(data[arrIndex]);
	} else {
		_successCallback();
	}
};
 

By using above recursive method you will get the callback when all records will be deleted from table and then you can do your rest functionality. 

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..