While I do understand that these questions are very similar, I'd like to see how I can solve my JSON issue, since this question deals with 3 functions, rather than two.
I was directed to this question: JavaScript closure inside loops – simple practical example
However, their situation is a lot more simple, and I've tried both answers to no avail. It might be possible that my implementation of their solutions was incorrect.
I've gotten myself in a bit of a bad situation here; I'm trying to use a getJSON method inside a getJSON method inside a forEach loop.
My main issue, is that certain portions of the loop are executing faster than others, switching around variables and therefore messing up the second part of getJSON. In the end, it'll crash with errors of the API not having such an object for certain JSON, even though I can check for it and it'll be there.
I think this issue would mean that I need these methods to work synchronously.
I'm using NodeJS, Require, and some various APIs. Both of my getJSONs, as seen, have callbacks that are being used. I think it's just that the first one is executing a lot faster than the second.
I also tried fooling around with wait and setTimeout methods to no avail :(
offer.items_to_receive.forEach(function(item){
function wait(callback, delay){
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + delay);
callback();
}
getJSON(firstjsonlink, function(json){
var name = json.result[item.classid].name;
var qualityString = json.result[item.classid].tags[0].internal_name;
var qualityInt = json.result[item.classid].app_data.quality;
var tradableString = "Untradable";
var craftableString = "Craftable";
if(json.result[item.classid].tradable == 1){
tradableString = "Tradable";
}
getJSON(secondjsonlink, function(jsonNew){
var value = jsonNew.response.items[name].prices[qualityInt][tradableString][craftableString][0].value_raw;
}
total += value; // total is in fact defined right before the top of the paste
});
});
});