SQLite回调高效解决方案 [英] SQLite callback efficient solution

查看:15
本文介绍了SQLite回调高效解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 JavaScript 运行一系列 SQLite 查询.这些查询获取多个表的最新更新时间戳.例如:

I would like to run a series of SQLite queries using JavaScript. These queries get the latest update timestamp of several tables. For example:

SELECT last_updated FROM students ORDER BY last_updated DESC LIMIT 1;

SELECT last_updated FROM docs ORDER BY last_updated DESC LIMIT 1;

SELECT last_updated FROM logs ORDER BY last_updated DESC LIMIT 1;

SELECT last_updated FROM requests ORDER BY last_updated DESC LIMIT 1;

然后我会将这些 last_updated 时间戳发送到服务器.当我想到如何做到这一点时,我会使用这样的东西:

Then I would send these last_updated timestamps to the server. When I think of how to do this, I would use something like this:

var message = {};
sql('QUERY 1',[],function(row){
    message.q1 = row.shift().shift(); // first row, first item
    sql('QUERY 2',[],function(row){
        message.q2 = row.shift().shift();
        sql('QUERY 3',[],function(row){
            message.q3 = row.shift().shift();
            sql('QUERY 4',[],function(row){
                message.q4 = row.shift().shift();
                $.ajax('submit.php',{ // tell the server these things.
                    data: message,
                    type: 'POST',
                    success: function(response) {
                        console.log('Server replied: '+response+'\n');
                    },
                    error: function() {
                        console.log('HUHU.\n');
                    }
                }
            });
        });
    });
});

这会起作用,但我发现由于嵌套的 SQL 调用,这非常低效.在某些情况下,我可能还需要来自 10 个不同表的数据.

This will work but I find this very inefficient becaue of the nested SQL calls. There might also be cases wherein I need the data from 10 different tables.

有没有更有效的方法来做到这一点?

Is there a more efficient way of doing this?

推荐答案

您可以做的一件事是并行"执行调用,并使用屏障"模式查看它们何时完成.

One thing you can do is do the calls "in parallel", and use a "barrier" pattern to see when they are done.

var calls_to_go = 4;
var callback = function(){
   calls_to_go -= 1;
   if(calls_to_go <= 0){
     do_ajax_stuff();
   }
}

sql('QUERY 1',[], callback);
sql('QUERY 2',[], callback);
sql('QUERY 3',[], callback);
sql('QUERY 4',[], callback);

当然,这个特定的代码只是为了提供一个想法.如果您使用这些异步编程库中的一个,它们都应该有一些功能可以使编写此类事情变得更加愉快,如果您仍然想手工做事情,则应确保事情更有条理,4"不是不是硬编码,等等.

Of course, this particular code is just to give an idea. If you use one of those async programming libraries they should all have some feature for making writing this sort of thing more pleasant and if you still want to do things by hand you should make sure that things are more organized, that the "4" isn't hardcoded, and so on.

这篇关于SQLite回调高效解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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