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

时间:2014-10-02 08:13:49

标签: javascript return-value web-sql

我想在WebSQL函数内的javascript中的数据库中返回特定表中的行数。以下是我的代码。

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


我是WebSQL的新手,而且对javascript也不熟悉 有什么建议?

2 个答案:

答案 0 :(得分:2)

你不能这样做:

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

你必须使用这样的回调:

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

并使用它:

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

答案 1 :(得分:1)

另一种方法是使用promises,这是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
}