The Json call is made but the code goes without waiting for it

Hi,

I guess I am using the wrong syntax as it seems the Jquery doesn’t wait for the value that I am calculating in my call


        var pComputedPrice = 0
        var pComputedDiscount = 0
        var pFinalPrice = 0

        $.getJSON("MyFunction_Json.aspx?P_Id=" + pP_Id + "&Qty="  + pQty,
            function (jsonData) {
                pComputedPrice = jsonData;
            });

        pComputedDiscount = Number((pComputedPrice / 100 * pDiscount));
        pFinalPrice = pComputedPrice - pComputedDiscount;

It appears the code shown below solved the issue, but is this a good way ?

// Set the global configs to synchronous 
$.ajaxSetup({
    async: false
});

// Your $.getJSON() request is now synchronous...

// Set the global configs back to asynchronous 
$.ajaxSetup({
    async: true
});

use the .done method to “wait” for a response.
https://api.jquery.com/jquery.getjson/

1 Like

For reference, this is the first “A” in “AJAX” - Asynchronous Javascript And XML.

Basically, the code says “You’ve asked me for that external resource. Rather than halting your program/script/browser/etc while waiting for it, you can keep going. I’ll handle the result when i’m done.” (Alternatively: "When I have success or fail")

1 Like

Essentially that’s code-blocking isn’t it? We’re saying while we wait for getJSON to fetch data nothing else can happen, no user interaction clicks etc. — I don’t know how Jquery handles this, so could be wrong.

Obviously that isn’t ideal and the reason the process should be asynchronous.

Just to add to that, ‘I might be done, but I have to wait my turn’.

This is opening a can of worms, but it is worth looking into how the event loop and call stack prioritise/order processes. I’ve used a promise and requestAnimationFrame here, but it’s the same principal e.g.

// global execution context [start]

// asynchronous callback will be passed to the macro-task queue
setTimeout(() => console.log(`I'm last`), 0)

Promise.resolve(`I'm second`)
  // asynchronous callback will be passed to the micro-task queue
  .then((message) => console.log(message))

// asynchronous callback will be passed to the micro-task queue
window.requestAnimationFrame(() => console.log(`I'm third`))

const x = 'first'
console.log(`I'm ${x}`)

// global execution context [end]

If you see the logged output you can see the global execution code is executed/completed synchronously (top to bottom) before the asynchronous operations.

There may well be better links, but just a quick google and a scan.

It should be noted this particular caveat about the synchronized requests:

Not sure if his query is being (erroneously?) flagged as jsonp one?

EDIT: Additional.