luciotato / waitfor

Sequential programming for node.js, end of callback hell / pyramid of doom
MIT License
531 stars 29 forks source link

sqlite3's prepare statement fails #37

Closed jcwren closed 9 years ago

jcwren commented 9 years ago

I'm using sqlite3's database#prepare statement, and neither wait.for() or wait.forMethod() returns correct results.

From the documentation:

Database#prepare(sql, [param, ...], [callback])

Prepares the SQL statement and optionally binds the specified parameters and calls the callback when done. The function returns a Statement object.

When preparing was successful, the first and only argument to the callback is null, otherwise it is the error object. When bind parameters are supplied, they are bound to the prepared statement before calling the callback.

This (normal form) works:

var stmt = db.prepare ("INSERT OR REPLACE INTO foo (a,b,c) VALUES (?,?,?)", function (err) {
  if (err) throw err;
});

No error occurs, and the statement is later used in a wait.forMethod (stmt, 'run', records);.

With wait.for():

var stmt = wait.for (db.prepare, "INSERT OR REPLACE INTO foo (a,b,c) VALUES (?,?,?)");

throws an error: TypeError: Database object expected

With wait.forMethod():

var stmt = wait.forMethod (db, 'prepare', "INSERT OR REPLACE INTO foo (a,b,c) VALUES (?,?,?)");

returns undefined.

This well could be a misunderstanding on my part, but shouldn't I be able to use prepare with one or the other wait() calls? I use wait.forMethod (db, 'run', 'BEGIN TRANSACTION'); without issues.

And thank you for an excellent package. It really turned some horribly nested callbacks into something readable.

luciotato commented 9 years ago

It seems not to be a standard async with a callback(err,data). You can try standardizing it: https://github.com/luciotato/waitfor#notes-on-non-standard-callbacks-eg-connectionquery-from-mysql

try this:

 db.prototype.prep = function(sql, stdCallback){ 
             var stmt = this.prepare(sql, function(err){ 
                                 return stdCallback(err, stmt); 
                         });
 }

var stmt = wait.forMethod (db, 'prep', "INSERT OR REPLACE INTO foo (a,b,c) VALUES (?,?,?)");
jcwren commented 9 years ago

Excellent. While it's technically not necessary, it does mean that I can have consistency, which makes for better readability. Thank you.