This question has already been answered:
There is such code:
var artAjaxRequest = new function () { var xhr; xhr = new XMLHttpRequest(); xhr.open('GET', '/assets/json/arts.json', true); xhr.send(); xhr.onload = function(){ // Π’ΡΡ ΠΌΡ ΠΏΠ°ΡΡΠΈΠΌ json ΠΈ ΡΠΎΡΠΌΠΈΡΡΠ΅ΠΌ ΠΌΠ°ΡΡΠΈΠ² ΠΊΠ°ΡΡΠΈΠ½ΠΎΠΊ } this.getNewArts = function(){ // ΠΡΠ° ΡΡΠ½ΠΊΡΠΈΡ Π·Π°Π½ΠΈΠΌΠ°Π΅ΡΡΡ ΡΠ΅ΠΌ, ΡΡΠΎ Π²ΡΠ²ΠΎΠ΄ΠΈΡ ΠΊΠ°ΡΡΠΈΠ½ΠΊΠΈ Π½Π° ΡΡΡΠ°Π½ΠΈΡΡ }; }(); This is all "housekeeping" through artAjaxRequest.getNewArts(); .
But there is a problem here: when I write somewhere in the code artAjaxRequest.getNewArts(); , the getNewArts code is being getNewArts , whereas json itself has not yet arrived and the onload function has not worked its way. Why? Because the ajax request is not executed as quickly as the browser understands the code.
Accordingly, json is not parsed, and errors occur in the getNewArts function.
And here's the question: how to make .getNewArts run after xhr.onload ?
But don't be in a hurry to put artAjaxRequest.getNewArts(); inside onload . The getNewArts() that the getNewArts() method will be called often, not just one time when json arrives.
I would be grateful for clarifications and advice on improving the composition of the code.
Π½Π΅ ΡΠΏΠ΅ΡΠΈΡΠ΅ ΠΏΠΎΠΌΠ΅ΡΠ°ΡΡ artAjaxRequest.getNewArts(); Π²Π½ΡΡΡΡ onloadΠ½Π΅ ΡΠΏΠ΅ΡΠΈΡΠ΅ ΠΏΠΎΠΌΠ΅ΡΠ°ΡΡ artAjaxRequest.getNewArts(); Π²Π½ΡΡΡΡ onloadIt is not clear why not. - vp_arth