0

I've been reading through different types of posts here regarding my topic but I couldn't fully understand the concept of closures and their scopes. I have the following code:

var result = loadFile('input/file.txt');

function loadFile(file) {
    var test;

    $.get(file)
    .done(function(data) {
        test = data.split("\r\n");
    })
    .fail(function(){
        alert("failed loading file");
    });

    return test;

}

I simply want to assign the closure value, that is the split, to the local variable one level above the .get function. Is this possible? In the example above the local test variable never gets populated.

Thank you for helping me!

Morty
  • 11
  • 3
  • 1
    `get` is an Asynchronous call...You are trying to eat the delivery pizza before it is delivered to your house. – epascarello Apr 15 '15 at 12:55
  • @epascarello Great analogy. It's not true that the "local test variable never gets populated" - here's one way to test - return function () { return test } instead. You'll notice that if you call that function immediately, test isn't populated, but if you call it later(after the ajax call is done), test would be populated. The problem is, you're returning test's value before it has been changed. – Sacho Apr 15 '15 at 12:57
  • Thank you both for clarifying this to me and pointing me to the right direction. I totally understand now! – Morty Apr 15 '15 at 14:02

0 Answers0