【问题标题】:Finish first ajax before firing the second, finish second ajax before firing third ajax inside loop在触发第二个之前完成第一个 ajax,在循环内触发第三个 ajax 之前完成第二个 ajax
【发布时间】:2016-12-13 09:58:36
【问题描述】:

我从我们的 api 得到这个 json 响应,我需要循环并为每个产品创建 woocommerce 产品或变体产品。

{
  "pagination": {
    "page": 1,
    "per_page": 50,
    "results": 2,
    "pages": 1,
    "deleted_product": 0
  },
  "products": [
    {
      "id": "02dcd191-aebf-11e6-f485-5abe3e19de38aotbb94CZY3STcO1MxQS1S",
      "name": "testProduct112312312312345325345",
      "description": null,
      "sku": "testProduct112312312312345325345",
      "active": 1,
      "cost_price": 0,
      "list_price": null,
      "sell_price": 17.28,
      "tax_value": 1.728,
      "tax_name": "Sales_tax_sample",
      "tax_rate": 0.1,
      "tax_id": "02dcd191-aebf-11e6-f485-1c85a7f11c83",
      "includes_tax": true,
      "quantity": null,
      "product_type": null,
      "update_at": "2016-08-05 03:42:14",
      "deleted_at": null,
      "images": [],
      "variants": [],
      "tags": [],
      "outlets": [
        {
          "outlet_id": "0a422413-2fb9-11e6-ff63-0b90c839fa9e",
          "name": "Main Outlet",
          "quantity": 10
        }
      ],
      "price_books": [
        {
          "id": "65f85250-5ce8-9295-59be-40d76716eb00",
          "price": 17.28
        }
      ],
      "brands": []
    },
    {
      "id": "02dcd191-aebf-11e6-f485-5abe44095b97aotbb94CZY3STcO1MxQS1S",
      "name": "var1444444444444444444444444444444444444444444",
      "description": "<p>jameshwart</p>",
      "sku": "testvar_23234",
      "active": 1,
      "cost_price": 0,
      "list_price": null,
      "sell_price": 7.49545,
      "tax_value": 0.74955,
      "tax_name": "Sales_tax_sample",
      "tax_rate": 0.1,
      "tax_id": "02dcd191-aebf-11e6-f485-1c85a7f11c83",
      "includes_tax": true,
      "quantity": null,
      "product_type": null,
      "update_at": "2016-08-05 05:55:55",
      "deleted_at": null,
      "images": [],
      "variants": [
        {
          "id": "02dcd191-aebf-11e6-f485-5abe44095b97aotbb94CZY3STcO1MxQS1S",
          "name": "var1444444444444444444444444444444444444444444 / Blue",
          "sku": "10017",
          "quantity": null,
          "tax_value": 0.74955,
          "tax_name": "Sales_tax_sample",
          "tax_rate": 0.1,
          "tax_id": "02dcd191-aebf-11e6-f485-1c85a7f11c83",
          "includes_tax": true,
          "list_price": null,
          "sell_price": 7.49545,
          "cost_price": 0,
          "option_one_name": "Colour",
          "option_one_value": "Blue",
          "option_two_name": null,
          "option_two_value": null,
          "option_three_name": null,
          "option_three_value": null,
          "update_at": "2016-08-05 05:55:55",
          "deleted_at": null,
          "outlets": [
            {
              "outlet_id": "0a422413-2fb9-11e6-ff63-0b90c839fa9e",
              "name": "Main Outlet",
              "quantity": 0
            }
          ],
          "price_books": [
            {
              "id": "b343e66b-33d1-41af-9969-9df911a29b7baotbb94CZY3STcO1MxQS1S",
              "price": 7.49545
            }
          ]
        },
        {
          "id": "02dcd191-aebf-11e6-f485-5abe45693e6caotbb94CZY3STcO1MxQS1S",
          "name": "var1444444444444444444444444444444444444444444 / Red",
          "sku": "sku_119",
          "quantity": null,
          "tax_value": 0.99773,
          "tax_name": "Sales_tax_sample",
          "tax_rate": 0.1,
          "tax_id": "02dcd191-aebf-11e6-f485-1c85a7f11c83",
          "includes_tax": true,
          "list_price": null,
          "sell_price": 9.97727,
          "cost_price": 0,
          "option_one_name": "Colour",
          "option_one_value": "Red",
          "option_two_name": null,
          "option_two_value": null,
          "option_three_name": null,
          "option_three_value": null,
          "update_at": "2016-08-05 05:55:55",
          "deleted_at": null,
          "outlets": [
            {
              "outlet_id": "0a422413-2fb9-11e6-ff63-0b90c839fa9e",
              "name": "Main Outlet",
              "quantity": 0
            }
          ],
          "price_books": [
            {
              "id": "fdd0f01b-a2c2-0263-b17c-3f63fdf0e6b8",
              "price": 9.97727
            }
          ]
        }
      ],
      "tags": [],
      "outlets": [
        {
          "outlet_id": "0a422413-2fb9-11e6-ff63-0b90c839fa9e",
          "name": "Main Outlet",
          "quantity": 0
        }
      ],
      "price_books": [
        {
          "id": "b343e66b-33d1-41af-9969-9df911a29b7baotbb94CZY3STcO1MxQS1S",
          "price": 7.49545
        }
      ],
      "brands": []
    }
  ]
}

从上面的 json 中可以看出,可能有许多可能的页面,每页最多 50 个产品。我已经编写了代码以获取第一页,如上面的示例 json 并循环遍历每个产品。下面是我的代码

function product_to_woo( page ){

            //check if page is undefined then we set it to one
            if(typeof page == 'undefined'){
                page = 1;
            }else if( page <= 0){
                //Make sure we always start to page 1
                page = 1;
            }
            var product_number = 0;

            get_product_by_page(page, function(res){
                var product_count = res.products.length;

                if(product_count > 0){

                    for( var i = 0; i < product_count; i++){


                        product = res.products[i];
                        if( product.deleted_at == null ){
                            product_number = i+1;
                        }


                        if(res.pagination.page > 1){
                            product_number += PER_PAGE;//PER_PAGE is constant value 50
                        }

                        var p_data = {
                            action              :   'import_to_woo',
                            page                :   res.pagination.page,
                            product_total_count :   res.pagination.results,
                            product             :   product,
                            product_number      :   product_number,
                            deleted_product     :   res.pagination.deleted_product
                        };

                        post_data(p_data,function(p_res){
                           //I have done some message for the users
                        });
                    }

                }



                if(res.pagination.page <= res.pagination.pages){

                    page = parseInt(res.pagination.page) + 1;

                    if(page <= res.pagination.pages){
                        product_to_woo(page);
                    }

                }

            });

    }

我的问题是在 for 循环中设置了 ajax 请求。它在第一个 ajax 请求完成之前发送另一个 ajax 请求并发送第三个 ajax 请求,即使第二个 ajax 尚未完成。

还有其他方法吗?但不同的是让第一个 ajax 在触发另一个第二个 ajax 之前完成,然后在第二个请求完成后也会触发第四个 ajax 请求,依此类推,直到没有留下的产品。

【问题讨论】:

    标签: jquery json ajax


    【解决方案1】:

    您可以在第一个 ajax 的 successCallback 内运行您的第二个 ajax。并在第一个 ajax 的 successCallback 内运行您的第三个 ajax。以此类推。

    //first ajax
    $.post("someurl.php", { data: someData }, function (response1) {
        //do work with the response of the ajax
        //...
    
        //second ajax
        $.post("someotherurl.php", { data: someOtherData }, function (response2) {
            //...
    
            //third ajax
            $.post("yetanotherurl.php", { data: yetAnotherData }, function (response3) {
                //...
            });
        });
    });
    

    管理此回调地狱的更好方法是使用jqXhr 对象的deferred 类似行为。


    在您的特定情况下,您正在在循环内进行并发 ajax 调用。假设您不知道确切的调用次数,则上述方法将不适用或充其量是非常麻烦的。但是您可以使用jQuery.Deferred()jQuery.when() 来确保所有之前的ajax 调用和所有相关工作在运行ajax 之前都已经完成。

    var defs = [];
    for (var i = 0; i < 3; i++) {
        var d = $.Deferred();
    
        //make sure to wait for all the previous ajax calls to get resolved
        $.when.apply(this, defs).done(function () {
            $.post("url", { data: someData }, function (response) {
                //do work with response
                //...
    
                d.resolve(); //resolve the deferred to let the next ajax know it is done
            });
        });
    
        defs.push(d);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多