0

I've written a small util for importing JSON files and store them in a variable. But sadly I'm using a deprecated function within the XMLHTTPRequest. I've been looking all over, but can't seem to find the right answer.

Purpose: Return JSON object from imported file

Problem: I can't seem to return a proper JSON object outside the onload event

var require = function (file) {
    var xmlhttp;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("GET", file, false);
    xmlhttp.send();

    return JSON.parse(xmlhttp.responseText);
};

This is how i use it:

var config = require("file.json");

What must I do to make this work without getting the following console alert:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Thanks in advance!

Geoffrey

  • Easiest would be to add an onload handler to the xmlhttp object and just do it async. – Shilly Apr 14 '17 at 12:38
  • Its not possible to return something asynchronously. Maybe `Promises` could be the right thing for you to avoid callback functions? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Teemoh Apr 14 '17 at 12:38
  • He's trying to use the deprecated sync version of xmlhttp. Just getting a normal async will be enough, promises can come later. Besides, a promise is just a wrapper for a callback, so if you want to avoid callbacks, promises won't work either. – Shilly Apr 14 '17 at 12:39
  • I fixed it by using a setInterval and clear the interval when a response has been caught from the xmlhttp object. Thanks all! –  Apr 20 '17 at 09:05

0 Answers0