I guess I have a relative simple question, but I keep thinking in circles and even Google is not giving me an answer I can work with.
Basically I am trying to copy some records that are stored locally using WebSQL. Copying is not the problem, but I need to know when all copy actions are finished before my program can proceed.
WebSQL calls are made asychronous so the only way for me to usually do these things is by using the callback function. However, because the queries are done within a for loop, I can't use the callback function as it will fire at the first completed query as shown in the code.
The code is as follows:
function copyRecords(old_parent_id, new_parent_id, callback){
var db = openDatabase('test', '1.0', 'test', 50 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM table WHERE parent_id = ?', [old_parent_id], function(tx, results){
for(var i = 0; i < results.rows.length; i++){
db.transaction(function (tx2) {
tx2.executeSql('INSERT INTO table (name, parent_id) VALUES (?, ?)', [results.rows.item(i).name, new_parent_id], callback);
})
}
});
});
}
I've also tried calling the callback function when i == results.rows.length
, but that does not asure me that all queries are completed.
I guess some of you have encountered the same issue before, so any help on how to solve this and make sure that the callback function is only called when the for loop is complete is much appreciated.
Thank you in advance.