Home Understand JavaScript Synchronous vs Asynchronous
Reply: 0

Understand JavaScript Synchronous vs Asynchronous

user2496
1#
user2496 Published in June 19, 2018, 7:51 pm

This question already has an answer here:

  • Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 6 answers

I am new to JavaScript, Node.js in particular, and I have 2 functions that I am trying to execute. One gets data from a file and passes it to a list, and the other reads from that list in order to get one of the lines from the text file. My code works flawlessly, except the second function executes before the first, which is obviously a problem considering the second function needs information from the first in order to execute successfully.

let names = [];

function loadNames() {
  var reader = new LineReader("names.txt");
  reader.on("line", function (line) {
  names.push(line);
  console.log("length " + names.length)
  });
}

function getName() {
  console.log(names.length);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      console.log("Loaded - " + name);
 }
  console.log("what is wrong with this thing?")
}

loadNames() getName()

Expected Output:

length 1
length 2
length 3
length 4
length 5
length 6
length 7
length 8
length 9
length 10
10
Loaded - 1
Loaded - 2
Loaded - 3
Loaded - 4
Loaded - 5
Loaded - 6
Loaded - 7
Loaded - 8
Loaded - 9
Loaded - 10
what is wrong with this thing?

Actual Output (besides everything in parenthesis):

0 (from getName -> console.log(names.length))
what is wrong with this thing? (from getName)
length 1 (from loadNames -> console.log("length" + names.length))
length 2 (from loadNames -> console.log("length" + names.length))
length 3 (from loadNames -> console.log("length" + names.length))
length 4 (from loadNames -> console.log("length" + names.length))
length 5 (from loadNames -> console.log("length" + names.length))
length 6 (from loadNames -> console.log("length" + names.length))
length 7 (from loadNames -> console.log("length" + names.length))
length 8 (from loadNames -> console.log("length" + names.length))
length 9 (from loadNames -> console.log("length" + names.length))
length 10 (from loadNames -> console.log("length" + names.length))
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.329527 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO