Okay, so I look around a lot of answers and none of them seems helpful in what I want to achieve. Say I have the following code:
var n = 0;
$.ajax({
...
success: function(data){
n = Math.floor((Math.random()*10) + 1);
somefunction(n);
}
});
console.log(n) // n would obviously be 0 again
I had done it by making it synchronous using async:false
, but from what I read, it's bad for the user experience as it freezes up the browser as it waits for result. how exactly do I implement the callback function in the above case to allow global variable n
to be modified after ajax call?
Async functions are executed in a different thread (non-blocking) thus the callback will be called past your next instruction:
console.log(n);
n
is set after the callback (success function) is called but the log is before the async function is done. An easy solution is to wrap your code in a function and call it after jQuery calls success function. Note that you won't need to reference the global variable as it will be set outside of the jQuery scope and accessible to operation_x
function scope.
var n = 0;
function operation_x(){
console.log(n); // n is set to random value
}
$.ajax({
...
success: function(data){
n = Math.floor((Math.random()*10) + 1);
somefunction(n);
operation_x();
}
});
console.log(n); // n is 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With