-1

I know that due the nature of asynchronous XMLHTTPRequest it is impossible to return the responseText value in javascript. I've managed to find a workaround the issue by calling a workaround function which pastes the reponseText into whatever ID I provide the function with. However now I've stumbled on the problem again as I need to retrieve a JSON file and return the value of it. I’ve tried injecting responseText into a provided variable however it did not work, I've also tried adding an “interface-like” file which would do that for me, however none of the above worked. Are there any knows workarounds the issue?

function httpGetJson( file, type) {
        self.httpState(true);
        try{
            var type = type || true;
            var http = self.http();
            http.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200){
                    returnJson(this.responseText);
                }
            }
            http.open("GET", "json/" + file, type);
            http.send();
        }catch (err){
            return log.error("http.httpGetJson", err.message);
        }
        self.httpState(false);
    }

see all on codepen http://codepen.io/mecostav/pen/JNdovR

Costa W
  • 1
  • 2

1 Answers1

0

You should add a callback, or a Promise. For example, your function receives a function

function httpGetJson(file, type, cb) {
    self.httpState(true);
    try{
        var type = type || true;
        var http = self.http();
        http.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200){
                cb(this.responseText);
            }
        }
        http.open("GET", "json/" + file, type);
        http.send();
    }catch (err){
        return log.error("http.httpGetJson", err.message);
    }
    self.httpState(false);
}

And then you can call it:

httpGetJson('foo', 'bar', function (result) {
    // do something with result
});

Instead of:

var result = httpGetJson('foo', 'bar');
// do something with result

The latter will simply not work with JS, don't try to 'overcome' that. If you really want it, there is a deprecated method for performing sync http requests, you can google that (but please, don't).

Luan Nico
  • 5,376
  • 2
  • 30
  • 60
  • I am aware of synchronous requests and am trying to avoid those at all costs as the UX will worsen drastically. – Costa W Apr 25 '17 at 11:12