0

I need a fresh pair of eyes on this simple bit of code, thank you.

var totalMessageCount = 0;
            $.get("/Messages/GetVendorMessageCount/", { vendorId: "@ViewBag.VendorId" })
                .done(function (data) {
                    totalMessageCount = totalMessageCount + Number(data);
                    $(".MessageCount").html(data);
                });
            $.get("/Messages/GetVendorNotifyCount/", { vendorId: "@ViewBag.VendorId" })
                .done(function (data) {
                    totalMessageCount = totalMessageCount + Number(data);
                    $(".NotifyCount").html(data);
                });
            $.get("/Messages/GetVendorTaskCount/", { vendorId: "@ViewBag.VendorId" })
                .done(function (data) {
                    totalMessageCount = totalMessageCount + Number(data);
                    $(".TaskCount").html(data);
                });
            console.log("-" + totalMessageCount);
            $(".TotalMessageCount").html(totalMessageCount);

My controller returns the correct int values for each .get and they are displaying correctly. The problem is totalMessageCount is zero at the end. So for some reason, the totalMessageCount = totalMessageCount + Number(data) line doesn't seem to be working. It's gotta be something stupid I'm doing, been a long day... thanks

J Benjamin
  • 4,722
  • 6
  • 29
  • 39
  • 1
    Because ajax is async. Your `$(".TotalMessageCount").html(totalMessageCount);` is executed before the controller methods return the values back to the client. Put that line of code in each `.done()` callback –  Dec 18 '16 at 00:20
  • yep, thanks. that did it. it's not pretty but I tucked that line in the last .get and works as intended. – J Benjamin Dec 18 '16 at 00:30
  • 2
    There is no guarantee that will work - the last `$.get()` may be completed before the previous ones –  Dec 18 '16 at 00:32
  • hehe, I was about to say "before you say anything, ....etc..etc....." what you said :) ugly bit of code though, should probably move all that into a single call...thanks for the assist – J Benjamin Dec 18 '16 at 00:35
  • Sounds like a good plan to me :) –  Dec 18 '16 at 00:36
  • All those jquery gets effectively return promises - you should be able to store the return value from the three `$.get` calls and pass them in to `$.when` to get a new promise that you can add `.done()` onto, that won't actually happen until all three are done. – PMV Dec 18 '16 at 04:31

0 Answers0