2

作業中のデータベース アプリケーションで問題が発生しています。SQL トランザクションが完了する前に、JavaScript 関数が進行し続けているようです。以下は、私が経験していることの非常に単純化されたバージョンです。実際の関数では、for ループの次の値に移動する前に、テーブルでいくつかの作業を実行しようとしています。forループですべてを実行してから、SQLトランザクションを完了するようです。

サンプルコードは次のとおりです。

function fillTables(){
    db.transaction(function (tx){
        for(var i=0; i<3; i++){
            console.log('Filling row '+i);
            tx.executeSql(
                        'INSERT INTO Numbers (Value) VALUES (?)',
                        [i],
                        function (){
                            console.log('Inserted Row');    
                        },
                        errorCB);
            console.log('moving on...');
        }
    });
}

私が期待するコンソールログは次のようになります。

Filling Row 0
Inserted Row
moving on...
Filling Row 1
Inserted Row
moving on... 
Filling Row 2
Inserted Row
moving on... 

しかし、私は得ています:

Filling row 0 
moving on... 
Filling row 1 
moving on... 
Filling row 2 
moving on... 
Inserted Row 
Inserted Row 
Inserted Row 

どうすれば望ましい結果を達成できるかについてのアイデアはありますか?

4

2 に答える 2

1

tx.executeSql()は非同期関数であり、適切に動作しています。同期方法を探して、応答を編集します。

したがって、私が読んだことによると、関数はHTML5仕様のためにのみ非同期です。また、何らかの方法で同期的に実行すると、「無効な状態」エラーが返されます。

于 2012-12-20T18:54:29.817 に答える
0

tx.executeSql() は非同期関数です。この場合、関数が完了したら再帰呼び出しを実行する必要があります。

function fillTables() {
    db.transaction(function (tx){
        var recursiveFunction = function (index, length) {
            if (index < length) {
                console.log('Filling row ' + index);
                tx.executeSql(
                    'INSERT INTO Numbers (Value) VALUES (?)',
                    [index],
                    function (){
                        console.log('Inserted Row');
                        console.log('moving on...');
                        recursiveFunction(++index, length);    
                    },
                    errorCB);
             }
        }

        recursiveFunction(0, 3);
    });
}
于 2012-12-20T19:00:57.947 に答える