xralf
xralf

Reputation: 3662

Problem with asynchronous database communication

I'm communicating with sqlite database in firefox extension. First, I used this synchronous code. Then I changed it to this asynchronous code but it ended with error
anchors[i] is undefined, Line 95
This change didn't help.

There seems to be some problem with variable scope.

thank you for help

Upvotes: 0

Views: 132

Answers (1)

Wladimir Palant
Wladimir Palant

Reputation: 57651

One problem is that anchors is apparently a node collection as returned by document.anchors. As such it isn't a fixed list, it will change if the document changes. It might happen that an anchor is removed from the document while your database query is running. To prevent an issue like this you can make a copy of the collection:

var anchors = Array.prototype.slice.apply(document.anchors);

This will make anchors a regular array that won't change unexpectedly.

The other issue is that all your closure functions use the same variable i (see https://developer.mozilla.org/en/JavaScript/Guide/Closures for more info). When handleResult executes i will have the value anchors.length because the loop is already finished. To prevent this you need to capture the "current" value of i, e.g. in the object property like this:

statement.executeAsync({
    anchorIndex: i,
    handleResult: function(aResultSet) {
        ...
        anchors[this.anchorIndex]
        ...
    }

Upvotes: 1

Related Questions