jquery asynchronous events issue
I am firing a database service in a loop and passing it a quantity variable which can change for each itteration. The problem is that because of its asynchronous tendencies, the quantity is always the that of the last itteration. How can I make sure to pass the right quantity on each itteration?
see code
pre
///
/// run on create_order success event
/// This will write the line items to the Order (LineItems Collection)
///
/// Parameters: None
///
/// Returns: None
///
function createOrderSuccess(data) {
console.log('Order table written successfully');
Code: Select all
//get the order id
var orderId = data._id;
console.log("Order ID = " + orderId);
//success function for get_product_id
function successFunction(data, quant, orderId) {
//
//
// The quant value above is always the same!
//
//
var productId = data[0]._id;
console.log("product ID = " + productId);
// now we have the orderid and product id we can write the lineItem to the collection
add_order_item.execute({
data: {
"ItemId": {'collName': 'ProductItems', '_id': productId},
"Quantity": quant,
"OrderId" : {'collName': 'Orders', '_id': orderId }
},
success: function(data) {
console.log("Line Item written successfully");
}
});
}
// now need to add the order items
var item;
var quantity;
for (i = 1; i < shoppingBasket.length; i++) {
//get item and quantity
quantity = shoppingBasket[i][1];
console.log("quantity = " + quantity);
item = shoppingBasket[i][0];
console.log("item = " + item);
//get product data
get_product_id.execute({
data: {
"where": '{"ItemName":"' + item + '"}'
},
success: function(data) {
successFunction(data, quantity, orderId);
}
});
} }
/pre