var idd;
$.each(data, function (i, items) { //1st each
$.each(items, function (j, item) { // 2nd each
console.log("Field:" + j + " Value:" + item);
if (j=="sha_id"){ idd=item; }
});
console.log("Items");
console.log("ID:" + idd);
db.transaction(function (tx) {
console.log("being inserted");
console.log("ID Inserting:" + idd);
//then some database insertion query
This is sample upper part script
Basically 1st .each will run 2 round and 2nd .each will run two round for each 1st .each
So in console log I expect to see
field …. value
field ….. value
Items
ID : 2
being inserted
ID Inserting : 2
field …. value
field ….. value
Items
ID : 3
being inserted
ID Inserting : 3
But what i am getting is this
field …. value
field ….. value
Items
ID : 2
field …. value
field ….. value
Items
ID : 3
being inserted
ID Inserting : 3
being inserted
ID Inserting : 3
Why my db.transaction is not executed just after console.log(“Items”) at first as they are in the same loop. Is there any code error i should correct ?
Presumably
db.transactionis asynchronous.This means the
$.eachloops continue to run, and don’t wait fordb.transactionto complete.When
db.transactionis finally complete, the callback you gave it is invoked. This happens (relatively) long after the$.eachloops have finished.The moral of the story is that any code that should wait for the
db.transactionto complete, must be invoked within thedb.transactioncallback you’re passing.