Make a method pause until another property is ready
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 opene开发者_StackOverflow社区d},
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?
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);
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())
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
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.
精彩评论