Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I guarantee execution of jQuery Each statement before continuing on?

My code is as follows:

$(".qtyfield").each(function (index) {
    if (this.value != "" && this.value > 0) {
        var fieldname = this.id;
        countme = countme + 1;
        var tmpProductID = fieldname.split("_")
        var ProductID = tmpProductID[1];
        var ShowPrice = $(this).closest('td').prev('td').text();
        var Quantity = this.value;
        ShowPrice = ShowPrice.replace("$", "");
        isItemInCart(ProductID).done(function () {
            if (isItemInCartVar) {
                updateQuantityByProductID(ProductID, Quantity);
            }
            else {
                addToCartWithQty(ProductID, ShowPrice, Quantity);
            }

        });
        this.value = '';
    }
});

I need to ensure that this code block completes (all ajax calls included) prior to running any further statements.

A couple of points..

  1. isItemInCart is a function with an Ajax Call
  2. updateQuantityByProductID is a function with an ajax call
  3. addToCartWithQty is a function with an ajax call
  4. I don't know how many items are in the each collection (it could change)
like image 844
TRaymond Avatar asked Dec 11 '25 08:12

TRaymond


1 Answers

My solution would be to consolidate all this logic in a single call, something like updateCart().

On the client side you would create a list of products that need to be updated, e.g.

[
  {productId: 123, quantity: 2, price: 123},
  {productId: 456, quantity: 1, price: 200}
]

This data gets sent to the server side where the session data will get updated with the new quantities. Basically, the code on the server side will perform the same logic as you have in all your individual calls, but it will be much faster because there's only a single request.

A single request also reduces the likelihood of session lock contention and improves the consistency of your cart state.

On the client side, there's the advantage of only a single callback function instead of having to create a pipe of individual requests that need to be synchronized (read: big pain in the ass).

like image 93
Ja͢ck Avatar answered Dec 12 '25 22:12

Ja͢ck