Pass in an array of Deferreds to $.when()

后端 未结 9 1240
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 22:20

Here\'s an contrived example of what\'s going on: http://jsfiddle.net/adamjford/YNGcm/20/

HTML:

Click me!
&l
9条回答
  •  广开言路
    2020-11-21 22:48

    I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

    Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

        // 1st
        function Outer() {
            var deferreds = GetAllData();
    
            $.when.apply($, deferreds).done(function () {
                // now you can do whatever you want with the updated page
            });
        }
    
        // 2nd
        function GetAllData() {
            var deferreds = [];
            $('.calculatedField').each(function (data) {
                deferreds.push(GetIndividualData($(this)));
            });
            return deferreds;
        }
    
        // 3rd
        function GetIndividualData(item) {
            var def = new $.Deferred();
            $.post('@Url.Action("GetData")', function (data) {
                item.html(data.valueFromAjax);
                def.resolve(data);
            });
            return def;
        }
    

提交回复
热议问题