Search code examples
javascriptnode.jscoffeescriptwaitnode-fibers

Node fibers/future callbacks hell


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.

Please, anyone can help me to find the solution ?


Solution

  • I solved this, in github I've followed this :

    "You need to be in a Fiber to be able to use wait.for. The ideal place to launch a fiber is when a request arrives, to handle it:"

    var server = http.createServer( function(req, res){ console.log('req!'); wait.launchFiber(handler,req,res); //handle in a fiber, keep node spinning }).listen(8000);

    And I was able to use wait.for correctly

    Thanks.