2

I did quite a bit of searching and got the feeling my question is answered, but I had trouble integrating available answers with my particular situation. This is my first-ever Javascript, and I apologize for almost certainly repeating a beginner-question that's probably been adequately answered for very similar contexts. Basically, I don't get why fishDirector's var queryDir is always holding an undefined value after fishTitle is called.

function fishDirector() {

var dir = "";
var req = new XMLHttpRequest();

var URL = "https://netflixroulette.net/api/api.php?";
var queryTypeDir "director=";
var queryDir = fishTitle();
console.log(queryDir);
console.log(dir);

req.open('GET', URL + queryTypeDir + queryDir, true);
req.addEventListener("load", function() {
    var response = JSON.parse(req.responseText);

req.send(null);
});
}

Above I naively tried to define var dir in the calling function to be updated by the called function, fishTitle:

function fishTitle() {

var req = new XMLHttpRequest();

var URL = "https://netflixroulette.net/api/api.php?";
var queryType = "title=";
var query = document.getElementById('form_search').value;


req.open('GET', URL + queryType + query, true);
req.addEventListener("load", function() {
    var response = JSON.parse(req.responseText);

    dir = dir + response.director;
    console.log(dir);
    return dir;
});
req.send(null);
return dir;
}

The dumbly-located return statements were an unguided effort to have the anonymous function let it's calling function know what dir is, and have that returned to fishDirector, which called fishTitle. I get the impression the value of dir is lost once the anonymous function terminates, but if so, how do I get it out of there?

Dumbdumbdumb. Sue me.

Kangles
  • 29
  • 1
  • `XMLHttpRequest` is set to `true` for asynchronous flag. `dir` is returned at `return dir` before `load` event. Also missing `=` at `var queryTypeDir "director=";` – guest271314 Mar 17 '17 at 20:21

1 Answers1

0

It's because it's an asynchronous ajax request. Tḧat means that you request is put in a different thread and your main thread continues to execute.

So you do var queryDir = fishTitle(); and it runs all the way to the end, starting another thread of execution and returning undefined.

LATER, when this other thread gets processed, it may set the dir value, but the main flux of execution has already finished.

Read guest271314 answer to see one of the ways of dealing with it. Educate yourself about ajax and asynchronous programming to improve this understanding.

Graham
  • 7,431
  • 18
  • 59
  • 84
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73
  • Thanks to you both! I tried to race into javascript and blew right past all requisite knowledge of asynchronous requests - and didn't even know enough to know that's what I didn't know. – Kangles Mar 17 '17 at 22:10
  • NP. If you find any answer usefull please accept/upvote. Thanks. – Nelson Teixeira Mar 17 '17 at 23:21