1

I'm using node.js to search through a sqlite table of books and returning only the books that are not checked out. My question is if the second function that I am passing into stmt.each() will wait for isCheckedOut() to finish before executing?

At the moment it seems to be waiting but I'm worried that if isCheckedOut() takes longer to execute (ie: larger database) then the second function will run too early and won't return all the results.

If the second function is running prematurely, how can I make it wait?

var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('database');

function showAvailableBooks(callback) {
    var stmt = db.prepare("SELECT * FROM books");
    var results = [];

    stmt.each(function (err, row) {

        isCheckedOut(row.Barcode, function (err, checkedOut) {
            if (!checkedOut) {
                results.push({Title: row.Title, Author: row.Author, CallNumber: row.CallNumber});
            }
        });

    }, function () {
        callback(results);
    });
}

showAvailableBooks(function () {
    console.log("# of results: " + results.length);
});
Floyd
  • 13
  • 3

1 Answers1

0

No, stmt.each won't wait for all the isCheckedOut calls to run their callbacks if they get deferred. Right now, being sqlite (no network latency) and small database it might work, but if you try a different, remote or bigger database it may not.

Rob W answered a similar question using a counter here: https://stackoverflow.com/a/21185103/4925989 , but there are also other ways to make your finish callback wait.

Community
  • 1
  • 1
florpor
  • 201
  • 1
  • 6