如何单独处理多个ajax调用以及最终结果

时间:2022-12-04 00:19:25

I am making ajax calls to get html data back and append it to my container. I also need the html to be rendered in a specific order. I am trying to take the approach of loading everything, then re-ordering as necessary but am running into difficulty getting the calls to resolve in order (i.e. render, then order html).

我正在进行ajax调用以获取html数据并将其附加到我的容器中。我还需要以特定顺序呈现html。我试图采取加载所有内容的方法,然后根据需要重新排序,但遇到困难,让顺序解决调用(即渲染,然后命令html)。

Code (edited for brevity):

代码(为简洁起见编辑):

var components = ["comp1","comp2","comp3"];

function setup() {
    var deferredComponentAdds = [];
    $.each(components, function (i, componentId) {
        deferredComponentAdds.push(
            addComponent(componentId)
        );
    });
    $.when.apply($, deferredComponentAdds).then(fixComponentOrder());
}

function addComponent(componentName) {
    return $.ajax({
        type: "GET",   
        url: "/LoadViewComponent?viewComponent=" + componentName,
        success: function(data) {
            $('#components').append(data);
        }
    });
}

function fixComponentOrder() { /* ordering logic */ }

There are two issues I am having. First, the fixComponentOrder() is being called before the addComponent().success result is processing. Second, the fixComponentOrder() is being called after each addComponent() call (this doesn't break anything, but it is needless).

我有两个问题。首先,在addComponent()。成功结果处理之前调用fixComponentOrder()。其次,在每次addComponent()调用之后调用fixComponentOrder()(这不会破坏任何东西,但它是不必要的)。

What I need is for the addComponent() to be called and resolve the success of all calls, then after all of those are called and resolved, call the fixComponentOrder() once at the end.

我需要的是调用addComponent()并解决所有调用的成功,然后在调用并解析所有调用之后,最后调用一次fixComponentOrder()。

I can alternatively just throw fixComponentOrder() in my success function, but then I still have the second issue of it being called each time which is non-optimal.

我也可以在我的成功函数中抛出fixComponentOrder(),但是我仍然有第二个问题,每次调用它都是非最优的。

Thanks,

Jeff

2 个解决方案

#1


3  

I had to do a similar thing recently

我最近不得不做类似的事情

var arrOfObj = []
$.ajax({
  type: "GET",
  url: "/LoadViewComponent?viewComponent=" + componentName,
  success: function (data) {
    arrOfObj.push(data)
    render()
  }
});


render(){
  var ordering = { 'Shirts': 0, 'Pants and Shorts': 1, 'Hats': 2, 'Accessories': 3, }
  $('#components').empty()
  arrOfObj.sort(function (a, b) {
    return (ordering[a.name] - ordering[b.name]) || a.name.localeCompare(b.name);
  }).forEach(function (obj) {
    $('#components').append(obj);
  });
}

Just make sure the ordering keys matches the component's name. I modified the code i am using, so make sure to test this before using :)

只需确保订购密钥与组件名称匹配即可。我修改了我正在使用的代码,所以一定要在使用前测试一下:)

#2


4  

I didnt test it yet but the logic should work using promise

我还没有测试它,但逻辑应该使用promise

We execute addComponent() once it resolve we execute another function

我们执行另一个函数后执行addComponent()

 const addComponent = componentName => { 
    return new Promise(resolve =>{
        console.log("Hello1")
        return $.ajax({
        type: "GET",   
        url: "/LoadViewComponent?viewComponent=" + componentName,
        success: function(data) {
            $('#components').append(data);
          resolve()
        }
         });  
       })
    }

    function fixComponentOrder(){
    return addComponent(componentName).then(()=>{/*Your next function to execute*/})
    }

     fixComponentOrder()

Once fixComponentOrder() get executed , it will start by executing addComponent() and once it resolve it will execute what ever function you executed in the then

一旦fixComponentOrder()执行,它将通过执行addComponent()开始,一旦它解决它将执行你在那时执行的任何功能

#1


3  

I had to do a similar thing recently

我最近不得不做类似的事情

var arrOfObj = []
$.ajax({
  type: "GET",
  url: "/LoadViewComponent?viewComponent=" + componentName,
  success: function (data) {
    arrOfObj.push(data)
    render()
  }
});


render(){
  var ordering = { 'Shirts': 0, 'Pants and Shorts': 1, 'Hats': 2, 'Accessories': 3, }
  $('#components').empty()
  arrOfObj.sort(function (a, b) {
    return (ordering[a.name] - ordering[b.name]) || a.name.localeCompare(b.name);
  }).forEach(function (obj) {
    $('#components').append(obj);
  });
}

Just make sure the ordering keys matches the component's name. I modified the code i am using, so make sure to test this before using :)

只需确保订购密钥与组件名称匹配即可。我修改了我正在使用的代码,所以一定要在使用前测试一下:)

#2


4  

I didnt test it yet but the logic should work using promise

我还没有测试它,但逻辑应该使用promise

We execute addComponent() once it resolve we execute another function

我们执行另一个函数后执行addComponent()

 const addComponent = componentName => { 
    return new Promise(resolve =>{
        console.log("Hello1")
        return $.ajax({
        type: "GET",   
        url: "/LoadViewComponent?viewComponent=" + componentName,
        success: function(data) {
            $('#components').append(data);
          resolve()
        }
         });  
       })
    }

    function fixComponentOrder(){
    return addComponent(componentName).then(()=>{/*Your next function to execute*/})
    }

     fixComponentOrder()

Once fixComponentOrder() get executed , it will start by executing addComponent() and once it resolve it will execute what ever function you executed in the then

一旦fixComponentOrder()执行,它将通过执行addComponent()开始,一旦它解决它将执行你在那时执行的任何功能