In the code at the end of this post, the variable pPrice is defined via
$(addProduct).attr(attrProductPrice); and then set in a JSON call via
$.getJSON(url, function(data) { console.log(data); pPrice = data.price; });
but after the synchronous .getJSON call, the value has returned to its original value.
How can I overwrite the definition of the definition of the lexically scoped variable via the .getJSON call? Source code is abbreviated to relevant part:
function addToCart(i,qty){
var pPrice = $(addProduct).attr(attrProductPrice); //original value
var url = '/pricefor/' + pId;
$.getJSON(url, function(data) { console.log(data); pPrice = data.price; }); // new value
console.log(pPrice); // new value lost! back to original value?!
}
The
getJSONcall is asynchronous. Your function isn’t invoked until the JSON is retrieved from the server. The timeline looks like this: