简体   繁体   English

从JavaScript函数中的WebSQL查询返回COUNT

[英]Return a COUNT from a WebSQL query in a javaScript function

I want to return the number of rows in a particular table in a database in WebSQL inside a javascript function. 我想在javascript函数中返回WebSQL数据库中特定表中的行数。 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. 我是WebSQL新手,也不熟悉javascript
Any suggestions? 有什么建议么?

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 );
});

Another way is to use promises, here is an example with the Jquery deferred object 另一种方法是使用Promise,这是Jquery延迟对象的示例

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM