0

I have an object used for interacting with an IndexedDB. It has a property ready that changes to 2 when the database has finished opening. How can I tell the read method to wait until this.ready == 2?

var db = {
    open: function() {//a callback sets this.ready to 2 when the database has been successfully opened},

    ready: 0,

    read: function() {
        if(!this.ready == 2) {//pause until this.ready == 2}

        ...
    }
}

Should I write a function using setTimeout to check this.ready every 100 milliseconds or is there a more elegant solution?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Andy
  • 3
  • 2
  • This might help http://stackoverflow.com/questions/5346694/how-to-implement-a-lock-in-javascript – Tija Aug 26 '11 at 18:50

4 Answers4

0

normally any pausing would need to be done in a different thread but im very new to javascript so it could be different. but u can also try to have the function return whatever data u need then feed it into function2 function2(function1())

owen gerig
  • 6,165
  • 6
  • 52
  • 91
0

A timeout (actually, probably an interval that cancels itself) is the only good way in JavaScript to "wait" for something. Otherwise, because there's only a single thread, you end up blocking all other JS Execution in the browser. The other option would be to have something call your function when the status becomes a 2 (use a callback).

The "waiting" is approached like so:

var myWait = setInterval(function () {
  if (status == 2) {
    clearInterval(myWait);

    myFunction();
  }
}, 100);
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
0

using getters and setters on the object you can define a custom callback when the ready is set, then run you code if / when it is set to 2 read here

rlemon
  • 17,518
  • 14
  • 92
  • 123
0

I agree with @g.d.d.c - You should switch your logic around to use callbacks. You already have a open callback (at least according to your code example), so why not simply invoke read when your open callback is done? Then there is no need to make a blocking operation in your script.

Tejs
  • 40,736
  • 10
  • 68
  • 86