readRecords recurring issue

I’m working with a database and now and then, the readRecords statement that was working, stops working, and I need to clear my cache and cookies, then restart my browser and then it works again. At this point, I can’t get past this issue. When I run my app the first time, readRecords works, numStudents is correct and the console displays the names.

Then, when I run it a second time with no changes, it doesn’t work. After readRecords, numStudents = 0.

So, I delete the cache and cookies, then restart the browser, and I get the first result again. Run it the second time, numStudents = 0 again…

The project - https://studio.code.org/projects/applab/rq_N7guIcYk8P7r4fDHOBqhLDxGdQ7iw2kG8FjK6jnM

Is there a known issue with readRecords? Am I doing something funky?

(Note: Much of this code is draft code. I’m only interested in the readRecords issue for now.)

Thank you for your time!

Carol

What I am seeing is called a race condition.

You have this code:

  resetStudents();
  getStudents ();
  learnNames();

getStudents spawns a thread to handle the return of records from the database. You then call learnNames which has this:

function learnNames () {
  currentNameIndex = -1;
  score = 0;
  tries = 0;
  learnNextName();
}

It sets currentNameIndex and calls learnNextName(). That in turns contains this:

    if (currentNameIndex == numStudents-1) // already handled last student
      setScreen ("5finalResults");
    else {

The race condition occurs when you don’t know which will execute first. The code above which does nothing if there are no students or the code that gets the students from the database and sets numStudents to something other than zero.

In your previous version you called learnNames from the function that is called after the database returns and thus no race condition.

Don,

Thanks for the info and your quick reply!

I moved learnNames() to inside the readRecords, which is funky from a readability perspective, but seems to work.

is it general best practice in App Lap to include any code that depends on the data at the ends of the readRecord block, to ensure it doesn’t run too soon?

Carol

Don - Well, I answered my own question. The callback feature is strange in an environment where the DB is small and local, but as long as it works. Thanks for the help. - Carol

There is a technique called lazy initialization. You have a flag that is set to if you have read the database or not. If not you call to read the database and quit. If the database has been read you skip the read and continue. This is another way to do that which is easier to look at and understand.

Don - Thank you for all your help! - Carol