2016-07-19 20 views
1

SELECT要求を開始する前に複数のINSERTが必要です。私の問題は、SELECTが起動したときにINSERTがまだ終了していないことです。データベース処理のための工場製Cordova SQLiteは挿入が完了するまで待つ


databaseFactory.js

factory.insertIntoTable= function (database, data) { 
    var sqlCommand = 'INSERT INTO blablabla'; 

    database.transaction(function(tx) { 
    database.executeSql(sqlCommand, [data.thingsToInsert], function (resultSet) { 
     console.log('success: insertIntoTable'); 
    }, function (error) { 
     console.log('SELECT error: ' + error.message); 
    }); 
    }, function(error) { 
    console.log('transaction error: ' + error.message); 
    database.close(); 
    }, function() { 
    console.log('transaction ok: insertIntoTable'); 
    }); 
}; 

をINSERTはとにかく正常に動作しているapp.js

ionic.Platform.ready(function() { 
    if (window.cordova && window.cordova.plugins.Keyboard) { 
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 
    cordova.plugins.Keyboard.disableScroll(true); 
    }; 

    if(window.StatusBar) { 
    StatusBar.styleDefault(); 
    } 

    db = window.sqlitePlugin.openDatabase({name: 'myDbName.db', location: 'default'}); 

    if (window.Connection) { 
    if (navigator.connection.type !== Connection.NONE) { 
     databaseFactory.createTables(db); 

     MyService.getStuffFromAPI().then(function(result) { 
     for (var index = 0; index < result[0].campaigns.length; index++) { 
      databaseFactory.insertIntoTable(db, result[0].campaigns[index]); 
     } 

     var selectResult = databaseFactory.selectFromCampaigns(); 

     console.log(selectResult); //This log comes earlier than the above inserts could finish. 

     }, function(result) { 
     console.log(result); 
     }); 
    } 
    } 
}); 

、私はそれを確認しました。

私はdatebase.transactionが非同期であることも知っているので、単一のdb.executeSQLコマンドでも試しましたが、$ q resolveを追加しても同じ問題がありました。私は本当に、いくつかの助けを使うことができました!

答えて

1

問題は、それが非同期関数そのものだから、私はdatabase.transaction(function (tx){})を使用方法だったと関数本体内部の私は同期CRUD操作を行うことができ、順番に実行されます。
app.js(固定)

ionic.Platform.ready(function() { 
    if (window.cordova && window.cordova.plugins.Keyboard) { 
    cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 
    cordova.plugins.Keyboard.disableScroll(true); 
    }; 

    if(window.StatusBar) { 
    StatusBar.styleDefault(); 
    } 

    db = window.sqlitePlugin.openDatabase({name: 'MagicalWonder.db', location: 'default'}); 

    if (window.Connection) { 
    if (navigator.connection.type !== Connection.NONE) { 
     MyService.getMyPreciousData().then(function(result) { 

     db.transaction(function(tx) { 
      databaseFactory.createTable(tx);    

      for (var index = 0; index < result[0].campaigns.length; index++) { 
      databaseFactory.insertIntoTable(tx, result[0].myPreciousData[index]); 
      } 
      // HERE I CAN MAKE THE SELECT REQUESTS 
     }, function(error) { 
      console.log('transaction error: ' + error.message); 
      database.close(); 
     }, function() { 
      console.log('transactions successfully done.'); 
     }); 
     }, function(result) { 
     console.log(result); 
     }); 
    } 
    } 
}); 

ファクトリメソッド(固定)

factory.insertIntoTable = function (tx, data) { 
    var sqlCommand = 'INSERT INTO wanders (' + 
        'id, ' + 
        'magic_spell) values (?,?)'; 

    tx.executeSql(sqlCommand, [data.id, data.magic_spell], function (tx, resultSet) { 
     console.log('Success: insertIntoBookOfWonder'); 
    }, function (tx, error) { 
    console.log('SELECT error: ' + error.message); 
    }); 
}; 
0

すべての挿入が約束を返します。それらの約束を一連の約束で守り、$ q.allを使ってそれらのすべてが完了するのを待つ。

例:

promises.push(yourService.insert(obj).then(function(result){ //"result" --> deferred.resolve(res); 
    //success code 
}, function(error){ //"error" --> deferred.reject(err); 
    //error code 
})); 

そして最後に::ファクトリメソッドは、すべての挿入では、そのオブジェクト

function insert(object){ 

    var deferred = $q.defer(); //IMPORTANT 

    var query = "INSERT INTO objectTable (attr1, attr2) VALUES (?,?)"; 
    $cordovaSQLite.execute(db, query, [object.attr1, object.attr2]).then(function(res) { //db object is the result of the openDB method 
     console.log("INSERT ID -> " + res.insertId); 
     deferred.resolve(res); //"return" res in the success method 
    }, function (err) { 
     console.error(JSON.stringify(err)); 
     deferred.reject(err); //"return" the error in the error method 
    }); 

    return deferred.promise; //the function returns the promise to wait for 
} 

を挿入するために使用さ

$q.all(promises).then(function(){//do your selects}, function(err){//error!}); 

はそれがお役に立てば幸いです。

$ qと$ q.allについての詳細情報:https://docs.angularjs.org/api/ng/service/$q#all

そして、もう一つの例:https://www.jonathanfielding.com/combining-promises-angular/

+0

'$のq.all(約束)も'リターンを約束。 '$ q.all(約束).then(function(){//成功すると、ここであなたの選択を行いますか?}、function(err){//コードはエラー時}}' 。 –

+0

ええ、私はそれをこのように変更し、まだ動作しません。 APIリクエストでは$ qではないので、終了したかどうかはわかりません。 SQLiteプラグインで試しましたか? – MagicDragon

+0

私は最後に解決策を見つけたと思います。 – MagicDragon

関連する問題