HTML5 Sequential execution
I have created a web storage for product details (productId, name, quantityonhand) and have populate records into it from the server. I have to validate whether the required quantity is available to accept the order.
The Product form has checkboxes (with name="product") for every product available in the web storage and a corresponding text input field to accept the quantity required.
The validation method is defined as follows.
function productValidation(){
for(i=0;i<document.Products.product.length;i++){
// checking whether the product has been checked / choosen
if (document.Products.product[i].checked==true){
var productId = document.Products.product[i].value;
var qty = document.Products.p[i].value;
var db = systemDB;
// validating the available quantity
db.transaction(
function(transaction){
transaction.executeSql('select * from product where productId=?开发者_Python百科;',
[productId],
function(transaction, results){
for (var j=0; j<results.rows.length; j++) {
var row = results.rows.item(j);
if (qty>row['qoh']){
alert(
row['productname']
+ ' is out of stock. We can serve you only '
+ row['qoh'] + ' quantities currently!');
document.Products.product[i].checked = false;
document.Products.p[i].value = 0;
}
}
});
}
);
}
}
return false;
}
When this code is executed, because of asynchronous nature of the db.transaction, the outer loop is getting executed and the validation is happening only for the last product choosen.
Help me to fix this. I want the execution happen sequentially.
Yuvi
Try chaining together calls in the callback function for db.transaction:
function productValidation(){
checkProductsSequential(document.Products.product, 0);
return false;
}
function checkProductsSequential(products, i)
{
if (i < products.length)
{
// checking whether the product has been checked / choosen
if (document.Products.product[i].checked==true){
var productId = document.Products.product[i].value;
var qty = document.Products.p[i].value;
var db = systemDB;
// validating the available quantity
db.transaction(
function(transaction){
transaction.executeSql('select * from product where productId=?;',
[productId],
function(transaction, results){
for (var j=0; j<results.rows.length; j++) {
var row = results.rows.item(j);
if (qty>row['qoh']){
alert(
row['productname']
+ ' is out of stock. We can serve you only '
+ row['qoh'] + ' quantities currently!');
document.Products.product[i].checked = false;
document.Products.p[i].value = 0;
}
}
checkProductsSequential(products, i + 1)
});
}
);
}
else
{
checkProductsSequential(products, i + 1)
}
}
}
精彩评论