SQLite plugin for Cordova: Code running backwards

2019-06-02 04:55发布

I'm new using Cordova and Mobile development in general, but I have a really strange behavior in my code. I'm using the SQLite plugin with ngCordova (I'm using Ionic) and what I want to do is very simple: If a table exist, then drop it or create if it doesn't exists.

I've created a service for the database operations (I don't know if is the best way to do it, but it keeps that kind of logic separated from controllers).

The logic is this:

app.js

angular.module('starter', ['ionic', 'ngCordova', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform, $ionicLoading, $timeout, initialService) {
    $ionicPlatform.ready(function() {
        if (!initialService.hasUsers()) { // If there's no table called Usuarios
            initialService.createDefaultUser(); // Create table and a record
        } else {
            $ionicLoading.show({
                template: 'Restableciendo...'
            });
            initialService.resetDatabase(); // Droping table

            $timeout(function() {
                $ionicLoading.hide();
            }, 3000);
      }
  });
})

services.js

angular.module('starter.services', ['ionic', 'ngCordova']).service('initialService', function($cordovaSQLite, $ionicPopup) {
    return {

        // Check if Usuarios table exists
        hasUsers: function() {
            if (ionic.Platform.isAndroid()) {
                db = $cordovaSQLite.openDB({
                    name: "com.pos.db",
                    iosDatabaseLocation: 'default'
                });
            } else {
                db = $cordovaSQLite.openDB({
                    name: "com.pos.db",
                    location: 2,
                    createFromLocation: 1
                });
            }

            var returnValue;
            db.transaction(
                function(tx) {
                    tx.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name='Usuarios'", [], function(tx, result) {
                        console.log('Existen ' + result.rows.length + ' tablas con el nombre Usuarios');
                        returnValue = (result.rows.length) ? true : false;
                    });
                }
            );
            return returnValue;

        },

        // Creates the Usuarios table and a testing record
        createDefaultUser: function() {
            var returnValue;
            console.log("creando tabla de usuarios");
            if (ionic.Platform.isAndroid()) {
                db = $cordovaSQLite.openDB({
                    name: "com.pos.db",
                    iosDatabaseLocation: 'default'
                });
            } else {
                db = $cordovaSQLite.openDB({
                    name: "com.pos.db",
                    location: 2,
                    createFromLocation: 1
                });
            }

            db.sqlBatch([
                'DROP TABLE IF EXISTS Usuarios',
                'CREATE TABLE Usuarios (idUsuario INTEGER PRIMARY KEY AUTOINCREMENT, usuario TEXT NOT NULL, tipoUsuario NUMERIC NOT NULL DEFAULT 0, password TEXT)',
                "INSERT INTO Usuarios (idUsuario,usuario,tipoUsuario,password) VALUES (1,'mike',0,'123');",
            ], function() {
                returnValue = true;
            }, function(error) {
                returnValue = false;
            });
            return returnValue;
        },

        // Drops the table
        resetDatabase: function() {
            var returnValue = false;
            console.log("Eliminando tabla de usuarios");
            db.transaction(
                function(tx) {
                    tx.executeSql("DROP TABLE IF EXISTS Usuarios", [], function(tx, result) {
                        returnValue = true;
                    });
                }
            );
            return returnValue;
        }
    };
});

I'm debugging with my cellphone and the chrome console and the order of the code isn't the same as the execution order:

Error

How can I make sure that all of this operations are being made in the right order?

1条回答
可以哭但决不认输i
2楼-- · 2019-06-02 05:39

I suppose your project embeds jquery.

You have to use the $.deferred() (and promise()) if you want to chain the execution of the queries as you want it (read about it first to understand the basic).

Then I suggest you to use the JS object approach.

JS Object approach and $.deferred apply to WebSQL (quite similar to SQLite) are shown as an answer to the question in this link.

查看更多
登录 后发表回答