从javaScript函数中的WebSQL查询返回COUNT [英] Return a COUNT from a WebSQL query in a javaScript function

查看:346
本文介绍了从javaScript函数中的WebSQL查询返回COUNT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



我是 WebSQL 而且还不熟悉 javascript

有什么建议吗?


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

推荐答案

另一种方法是使用promises,这里是一个Jquery延迟对象的例子

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
}

这篇关于从javaScript函数中的WebSQL查询返回COUNT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆