Monday, 17 April 2017

Running node sqlite3 code synchronously

I'm having trouble adjusting to the async-first nature of node / js / typescript. This intent of this little function should be pretty clear: it takes a database and returns an array of courses that are listed in that database.

The problem is that the return statement gets run before any of the database operations have run, and I get an empty list. When I set a breakpoint inside the database each loop, I can see that the rows are being found and that courses are being put into ret one by one, but these courses never become visible in the scope where courseList() was called.

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

Suggestions?



via NiloCK

No comments:

Post a Comment