同步运行节点sqlite3代码

时间:2017-04-17 20:15:17

标签: node.js typescript sqlite

我无法适应node / js / typescript的异步优先性质。这个小函数的这个意图应该非常清楚:它需要一个数据库并返回该数据库中列出的一系列课程。

问题是return语句在任何数据库操作运行之前运行,我得到一个空列表。当我在数据库each循环中设置一个断点时,我可以看到正在找到这些行,并且这些课程将被逐一放入ret,但是这些课程在所在的范围内永远不可见courseList()被召唤。

const courseList = (database: sqlite3.Database): Course[] => {
    let ret = new Array<Course>();

    database.serialize();
    database.each("select ID, Title from Course", (err: Error, row: Object) => {
        ret.push(new Course(
            row.ID,
            row.Title
        ))
    })

    return ret;
}

建议?

调用代码只是想打印有关课程的信息。例如:

let courses = courseList(db);
console.log(courses.length); // logs 0, even though the db contains courses

1 个答案:

答案 0 :(得分:2)

const courseList = (database: sqlite3.Database, complete): Course[] => { let ret = new Array<Course>(); database.serialize(); database.each("select ID, Title from Course", (err: Error, row: Object) => { ret.push(new Course( row.ID, row.Title )) }, complete); return ret; } let courses = courseList(db, () => { console.log(courses.length); }); 需要完整的回调。用它来恢复,例如

//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .


var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function(){
        this.classList.toggle("active");
        var panel = this.nextElementSibling;
        if (panel.style.display === "block") {
            panel.style.display = "none";
        } else {
            panel.style.display = "block";
        }
    }
}

更多