Return a COUNT from a WebSQL query in a javaScript function

帅比萌擦擦* 提交于 2019-12-22 12:33:13

问题


I want to return the number of rows in a particular table in a database in WebSQL inside a javascript function. Below is my code.

function getCustomerCount(){    
    var count = 0;  
    db.transaction(function(tx) {   
    tx.executeSql('SELECT * FROM contacts', [], function(tx, results) {
             count = results.rows.length;   
        });
    });
    return count;
}


I am new to WebSQL and rather unfamiliar with javascript also.
Any suggestions?


回答1:


Another way is to use promises, here is an example with the Jquery deferred object

function getCustomerCount() {
    //setup the deferred object
    var defer = $.Deferred();
    var count = 0;
    db.transaction(function(tx) {
        tx.executeSql('SELECT * FROM contacts', [], function(tx, results) {
            //resolve the promise passing the count data
            defer.resolve(results.rows.length);
        });
    });

    //return a promise
    return defer.promise();
}

var countPromise = getCustomerCount();

//when the promise is resolved do something with the data
$.when(countPromise).done(function(count) {
    //now use count, could be you call another function that needs to use count,
    exampleThatUsesCount(count);
   //or assign it to another variable, or trigger an event that someone else in you app is    listening for
});


function exampleThatUsesCount(count) {
    //do something that uses count here
}



回答2:


You can't do this:

function getCustomerCount(){    
    var count = 0;  
    db.transaction(function(tx) {   
    tx.executeSql('SELECT * FROM contacts', [], function(tx, results) {
             // this function is called when the executeSql is ended
             count = results.rows.length;   
        });
    });
    // This returns always 0!
    return count;
}

You have to use callbacks like so:

function getCustomerCount( callback ){    
    var count = 0;  
    db.transaction(function(tx) {   
    tx.executeSql('SELECT * FROM contacts', [], function(tx, results) {
             // this function is called when the executeSql is ended
             count = results.rows.length;
             callback( count );   // <-- call the callback when is done   
        });
    });
}

And use it like:

getCustomerCount( function( count ) {
    // do what you want with the count
    console.log( 'The number of rows is: '+ count );
});


来源:https://stackoverflow.com/questions/26156768/return-a-count-from-a-websql-query-in-a-javascript-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!