0

How to get a data.json

{"key1":"val1","key2":"val2"}

with a function

var getJSON = function (url) {
    var response = null;
    return (function () {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.responseType = 'json';
        xhr.onload = function () {
            response = xhr.status == 200 ? xhr.response : xhr.status;
        };
        xhr.send();
    })();
    return response;
};

That the code

console.log(1);
console.log(getJSON('http://localhost/myproject/data.json'));
console.log(3);

gives

1
{"key1":"val1","key2":"val2"}
3

? Now it gives

1
null
3

Thank you

user2301515
  • 4,903
  • 6
  • 30
  • 46
  • 1
    run your console logs in the callback after assigning response. – dandavis Sep 16 '15 at 17:38
  • or you can use a promise: https://www.promisejs.org/ or for ES6 https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise – Lucas Sep 16 '15 at 17:40
  • 1
    You're are runing asynchronous request and this is taken out of te normal execution flow. You should use callback or promises. Chek this [stackoverflow question](http://stackoverflow.com/questions/14220321/) – Viktor Bahtev Sep 16 '15 at 17:45

1 Answers1

-1

Using promises.

Create the promise (check the second line in the code block below):

var getJSON = function (url) {
    return new Promise(function(){
        var response = null;
        return (function () {
            var xhr = new XMLHttpRequest();
            xhr.open('get', url, true);
            xhr.responseType = 'json';
            xhr.onload = function () {
                response = xhr.status == 200 ? xhr.response : xhr.status;
            };
            xhr.send();
        })();
        return response;
    })
};

Use .then syntax to console.log

console.log(1);
getJSON('http://localhost/myproject/data.json').then(function(response){
    console.log(response);
    return;
});
console.log(3);

It is gonna print 1,3 and then your data, synce the ajax call is async.

For reference: http://eloquentjavascript.net/17_http.html or official docs: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise

Lucas
  • 378
  • 1
  • 10
  • You never call `succeed` or `fail`. – Felix Kling Sep 16 '15 at 17:51
  • 1
    My point was that you *have* to call them at some point. Otherwise the promise is never going to be resolved or rejected. Simply copying the OP's code inside the promise callback doesn't magically solve the problem. Look at the examples you linked to. – Felix Kling Sep 16 '15 at 17:55
  • I want to such getJSON that returns the value and that is usable to aply in var resp = getJSON (url); in right time. – user2301515 Sep 16 '15 at 17:56
  • 1
    @user2301515: You want something that is impossible. Don't fight the asynchronous nature of JavaScript, embrace it. – Felix Kling Sep 16 '15 at 17:56