简体   繁体   English

在继续之前,我如何保证执行jQuery Every语句?

[英]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. 在运行任何进一步的语句之前,我需要确保此代码块完成(包括所有ajax调用)。

A couple of points.. 几点......

  1. isItemInCart is a function with an Ajax Call isItemInCart是一个带有Ajax调用的函数
  2. updateQuantityByProductID is a function with an ajax call updateQuantityByProductID是一个带有ajax调用的函数
  3. addToCartWithQty is a function with an ajax call addToCartWithQty是一个带有ajax调用的函数
  4. I don't know how many items are in the each collection (it could change) 我不知道每个集合中有多少项(它可能会改变)

I'd refactor the code so that the each loop is server side. 我将重构代码,以便each循环都是服务器端。 This way you can prepare the array on the client, send it with ajax (with a unique call) and then unpack it on the server where you'll have the each loop. 这样,您可以在客户端上准备阵列,使用ajax(使用唯一调用)发送它,然后将其解压缩到您将拥有each循环的服务器上。 What if your each loop is of billions of elements? 如果你的每个循环都有数十亿个元素怎么办? Multiply that by the length of an html header. 乘以html标头的长度。

Instead, you could just prepare the array like this. 相反,你可以像这样准备数组。

var serverSide = [];

$(".qtyfield").each(function (index) {

    serverSide.push("the data you need");

});

you could then send it up as a JSON string 然后你可以把它作为JSON字符串发送出去

var myArg = JSON.stringify(serverSide)

or a comma separated list (for simpler structures) 或以逗号分隔的列表(对于更简单的结构)

var myArg = serverSide.join(',');

and have a unique ajax call which can return any value/error message 并有一个唯一的ajax调用,可以返回任何值/错误消息

$.post("link", myArg).success(function(data){ alert("data"); })

I don't know which server side support you have but if you're using PHP you may decode the JSON string with json_decode . 我不知道你有哪个服务器端支持,但如果你使用PHP,你可以使用json_decode解码JSON字符串。

If you're using C#, you may want to have a look at JSON.net . 如果您使用的是C#,您可能需要查看JSON.net

Either way, you'll have much more flexibility like this. 无论哪种方式,你都会有更多这样的灵活性。 On the contrary, while doing an each loop on the client IS possible it is not the best solution. 相反,在客户端上执行每个循环时,它可能不是最佳解决方案。 Ajax calls have headers. Ajax调用有标题。

My solution would be to consolidate all this logic in a single call, something like updateCart() . 我的解决方案是在一次调用中整合所有这些逻辑,比如updateCart()

On the client side you would create a list of products that need to be updated, eg 在客户端,您将创建需要更新的产品列表,例如

[
  {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). 在客户端,只有一个回调函数的优点,而不是必须创建需要同步的单个请求的管道(读取:屁股中的巨大痛苦)。

Look for jQuery deferreds. 寻找jQuery延迟。 Every $.ajax call returns a 'promise' you can wait for to be resolved: 每个$.ajax调用都会返回一个“promise”,您可以等待解析:

var promise1 = $.ajax(...)
var promise2 = $.ajax(...)

Then wait for them to be resolved: 然后等待他们解决:

$.when(promise1, promise2).then(function(){
  //ready to rumble
});

As you mentioned you don't know how many items are in each collection, simply push each promise into an array, which can be used in $.when as follows: 正如您所提到的,您不知道每个集合中有多少项,只需将每个promise推送到一个数组中,该数组可以在$.when ,如下所示:

var promises = [];
promises.push($.ajax(...));
$.when.apply(this, promises).then(function(){...});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让JQuery语句等待完成,然后再继续?> - How do I get a JQuery statement to wait until it's completed before continuing?> 如何确保jQuery $ .each在继续之前完成 - How to ensure jQuery $.each is finished before continuing waiting for.each 在继续之前完成(jquery) - waiting for .each to finish before continuing (jquery) 如何保证在使用 useState 添加之前调用重置 - How do I guarantee that reset is called before add using useState 如果单击第二个元素,jQuery each()不会继续执行第一个元素的代码? - jQuery each() not continuing code execution for first element if a second element was clicked? jquery .ee等待函数在继续循环之前完成 - jquery .each waiting for function to finish before continuing through loop 如何在jQuery的“ .EACH”函数内执行“ CONTINUE”语句? - How do I execute a “CONTINUE” statement inside a “.EACH” function of jQuery? 在继续执行之前,如何等待javascript承诺返回值? - How to wait for javascript promise to return value before continuing execution? 如何在继续执行功能之前在单独的模态中等待用户操作? - How to wait for user action in separate Modal before continuing function execution? 如何在继续执行之前等待单独的 function 中的 API 响应? - How to wait for API response in separate function before continuing execution?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM