0

I am learning the basics of AJAX, and I am trying to store the result of the call in a variable. I have a data.txt file with this object:

[
{ "id": "5688","name": "  Jorge Luis Borges"},
{ "id": "5799","name": "  Lewis Carroll"}
]

And I am calling it with this call:

var object = "No object";
function requestFunction(url){
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.addEventListener("load", function() {
        object = this.response;
    });
    request.send(null);
    return object;
};
console.log(requestFunction("data.txt"));

I don't know why, but result = this.response doesn't affect to the variable where I want to store the result, and the console outputs its original value: No object.

Any idea why?


EDIT: I have been reading the fantastics responses in How do I return the response from an asynchronous call?, and I updated the function to include a callback that, when called, output the result:

function requestFunction(url){
    var request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.addEventListener("load", function() {
        outputFunction(this.response); // The callback
    });
    request.send(null);
};

// This is the callback
function outputFunction(a){
    console.log(a);
};

requestFunction("data.txt");

It works. Now, inside the callback, I want to store the result in a variable, and use it outside the function. Something like:

// This is the callback
var storedObject = "Empty";
function outputFunction(a){
    storedObject = a;
    return storedObject;
};

But again, it doesn't works. ¿Is because the same reason as the previous code?

1 Answers1

0
request.addEventListener("load", function() {
        object = this.response;
    });

is called asynchronously

object = this.response;

would be updated later, your code

console.log(requestFunction("data.txt"));

doesn't wait for it to finish updating, hence prints the orignal value

marvel308
  • 10,288
  • 1
  • 21
  • 32
  • 1
    No its not an async function. The function is called asynchronously... – Jonas Wilms Aug 22 '17 at 12:21
  • Yes I see it can lead to misunderstanding, edited – marvel308 Aug 22 '17 at 12:23
  • Ok, checking [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)… –  Aug 22 '17 at 12:29
  • requestFunction() would have to call a callback or return a promise, you can access the variable once the callback is called or wait for Promise.then() – marvel308 Aug 22 '17 at 12:34
  • Ok, I wrote a callback, but I can't store the value of the object in a variable! I will update the question. –  Aug 22 '17 at 19:40