How to make fibrous wait in Node.js?

985 views Asked by At

I'm new to Node.js, and realized that one of the big differences with it and client side javascript is how asynchronous everything is.

To try and address this, I'm attempting to use fibrous to turn my code back into a more functional style of programming, but having some problems:

How can I make the following fibrous code work ?

for example, the I'd like the following code to print 1,2,3, but it prints 1,3,2

function test()
{
  var fibrous = require('fibrous');
  var fs = require('fs');

  fibrous.run(function() { 
    var data = fs.sync.readFile('/etc/passwd');
    console.log('2');
  });
}

function runTest()
{
  console.log('1');
  test();
  console.log('3');
}

runTest();

// This prints 1,3,2 to the console, not 1,2,3 as I'd like.

in a real use case, the above routine would be wrap a DB method that runs async, and make it so I could write things like:

var dbTable = new dbTableWrapper();
var data = dbTable.getData();

/*
 ... do things with the data. 
 The "getData" routine is the same as my "test" function above.
*/
2

There are 2 answers

1
Jonathan Lonowski On BEST ANSWER

Is the answer to run the (newly added) "runTest" routine using a fibrous.run call itself?

That's part of it, yeah. Fibrous will need to call runTest itself to be able to manage its execution.

Then, test just needs to be wrapped rather than .run():

var test = fibrous(function () {
    var data = fs.sync.readFile('/etc/passwd');
    console.log('2');
});

And should be called with .sync():

test.sync();

var fibrous = require('fibrous');
var fs = require('fs');

var test = fibrous(function () {
  var data = fs.sync.readFile('/etc/passwd');
  console.log('2');
});

function runTest() {
  console.log('1');
  test.sync();
  console.log('3');
}

fibrous.run(runTest);
0
Murat On

Other a Express using :

 var express = require('express');
 var router = express.Router();
 var fibrous = require('fibrous');

 router.use(fibrous.middleware);

 router.get('/sync', function(req, res, next) {

   var order_categories = Order_Category.sync.list(options);
   console.log("Order_Category count : " , order_categories.length);

   var content_tags = Content_Tag.sync.list(options);
   console.log("content_tags count : " , content_tags.length);

   var creatives = Creative.sync.list(options);
   console.log("creatives count : " , creatives.length);

   return res.send( {
      order_categories: order_categories,
      content_tags: content_tags,
      creatives: creatives
      }
   );

 });