0

I want to print information from data base. I am doing it in this way: I have global array of itmes. 1. function with ajax get request to server that fetch all records and put the records data in the global array. 2. function that prints the data from the global array.

var items = []
function initPage() {
  getData(); / function that gets data from database and put in array
  printData(); / function that prints data to html
}

My Question is: I am running this all in my computer so it is all running fast and I dont have issues. But if I will move all to the internet and the query will run slower, will I have issues with the printData function? May it run before getData will finish? Or it waits for getData to finish?

What is the best way to deal with this kind of situations?

Thanks Alon

Alon Galpe
  • 55
  • 3
  • 10
  • Please can you post your functions `getData()` and `printData()`? You could send your `printData()` to `getData()` and make it the event handler for when you get a response. – Matthew Spence Nov 25 '17 at 16:33

1 Answers1

1

Yes, you can very well have problem with printData function because getData can take any amount of time or even timeout.

Javascript promise is your best friend in such situations :-)

Your getData function should do something like this:

function getData() {
  var url = 'http://blah.com/blah';
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = () => resolve(xhr.responseText);
    xhr.onerror = () => reject(xhr.statusText);
    xhr.send();
  });
}

Change your code like this:

var items = []
function initPage() {
  getData().then(
    function(data) {
      printData(data);
    },
    function(error) {
      printMessage(error);
    }
  );
}
RaviH
  • 3,544
  • 2
  • 15
  • 14