Make a function call for SQL web query

The Primecheck function should return true or false whether the passed number is prime or not. If the number is prime, the function adds it to the PRIMES table. This is the sieve algorithm of Eratosthenes, but it is not finished yet.

function primecheck (number) {
    var isprime = true;
        if (number%10 == 1 || number%10 == 3 || number%10 == 7 || number%10 == 9) {
        db.transaction(function (tx) {
            tx.executeSql('SELECT * from Primes', [], function (tx, result) {
                for (var i = 1; i < result.rows.length; i++) {
                    if (number%result.rows.item(i)['prime'] == 0) {
                        isprime = false;
                        break;
                    }
                }
                if (isprime) {
                    tx.executeSql('INSERT INTO PRIMES (prime) values (?)', [number]);
                }
                return isprime;
            }, null);
        }, null, null);

    }
    else {
        isprime = false;
        return isprime;
    }
}

Problem: when I pass numbers that do not end with 1, 3, 7, 9, the function returns true, this is normal. But when I pass other numbers, the function returns undefined. I suppose because the function call does not "wait" for the completion of the SQL query, so I have to use some callback functions. But that did not work.

+5
source share
1 answer

, , . ( , , - JavaScript.) , .

:

var isprime = primecheck(someNum);
// now do something with isprime

:

primecheck(someNum, function(isprime) {
    // now do something with isprime
});

return:

function primecheck (number, callback) {
    var isprime = true;
        if (number%10 == 1 || number%10 == 3 || number%10 == 7 || number%10 == 9) {
        db.transaction(function (tx) {
            tx.executeSql('SELECT * from Primes', [], function (tx, result) {
                //....
                callback(isprime);
            }, null);
        }, null, null);
    }
    else {
        isprime = false;
        callback(isprime);
    }
}

primecheck , , primecheck, isprime , primecheck .

+7

All Articles