lundi 21 mars 2016

Sqlite transaction and forEach

I have a function to execute some sql inside a forEach, I'm trying to deal with the promises, but there's no way to resolve them...

This is my code:

this.truncateTables = function () {
    var deferred = $q.defer();
    var promises = [];
    var tables = new Array('friends', 'settings', 'rol', 'user');
    tables.forEach(function (table) {
        var query = "DELETE FROM '" + table + "';";
        db.transaction(function (tx) {
            console.debug(query);
            tx.executeSql(query, [], function (tx, res) {
                deferred.resolve(res);
            }, function (tx, error) {
                deferred.reject(error);
            });
        });
        promises.push(deferred.promise);
    });

    return $q.all(promises);
};

And here I use this function:

$promise = transactionSqlService.truncateTables();
$promise.then(function(data){
     console.debug(data);
     $state.go('site.login');
},function(error){
     console.debug(error);
});

My problem is that only the first and second (sometimes only first) tables are emptied... I can see in the console how the $promise.then() is executing before all the querys have done.

What am I doing wrong? Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire