luciotato / waitfor

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

Mysql/Node/Wait.for issue #19

Closed jr-k closed 10 years ago

jr-k commented 10 years ago

I've tried to use the wait.for.js library in my node.js project and I fail to get database data from a query.

Here is the exemple (We are in a Database Class in coffeescript) :

execute: (sqlOrder) ->  
       resultSet = ""
       this.connection.query(sqlOrder,(err,results,fields) =>
         resultSet = results;
       )
       console.log results 

But in fact this can't work with callback process

Then I used "Wait.for" and tried to follow the database exemple "https://github.com/luciotato/waitfor" but there is a problem, where is the wait.launchFiber(); line ?

So I tried... But not working

query2 : ( sql, callback ) =>
        wait.for(@connection.query(sql,(err, result, field)->
            data = {results:result, fields:field}
            callback(err,data)
        ))

    back : (err,data) ->
        @result = data
        console.log("I'm in back")

    prepare: (strOrder) =>
        wait.launchFiber(@query2,strOrder,@back);
        console.log(@result)

The problem is, there is an instance of a Class "A" which call the method execute("Select * from my_table"), and the Class "B" with its method "execute(strOrder)" return an array or an object of the results.

I also tried :

var someObjects = wait.forMethod(@connection,"query",strOrder)

Please, anyone can help me to find the solution ?

ryuken commented 10 years ago

var wait = require("wait.for")

connection = mysql.createConnection({host: 'localhost', user: 'root', password: 'root', database: 'test'})

var result = wait.forMethod(connection, "query", sql, params)

This works for me

luciotato commented 10 years ago

Also note that wait.for works only with standardized callbacks, a standardized callback always returns (err,data) in that order.

A solution for the sql.query method and any other non-standard callbacks is to create a wrapper function standardizing the callback, e.g.:

 connection.prototype.q = function(sql, params, stdCallback){ 
             this.query(sql,params, function(err,rows,columns){ 
                                 return stdCallback(err,{rows:rows,columns:columns}); 
                         });
 }

all wrappers are simple functions standardizing the non-standard callback.

try {
  var result = wait.forMethod(connection, "q", options.sql, options.params); 
  console.log(result.rows);
  console.log(result.columns);
} 
catch(err) {
   console.log(err);
}