如何在Node.js中进行纤维等待?

我是Node.js的新手,并意识到它与客户端JavaScript的巨大差异之一就是一切都是asynchronous的。

为了试图解决这个问题,我试图使用fibrous把我的代码转换成更实用的编程风格,但是有一些问题:

我怎样才能使下面的纤维代码工作?

例如,我想要下面的代码打印1,2,3,但它打印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. 

在一个真实的用例中,上面的例程将会包装一个运行asynchronous的DB方法,并且可以编写如下的东西:

 var dbTable = new dbTableWrapper(); var data = dbTable.getData(); /* ... do things with the data. The "getData" routine is the same as my "test" function above. */ 

是使用一个fibrous.run调用本身来运行(新增加的)“runTest”例程的答案吗?

这是它的一部分,是的。 Fibrous将需要调用runTest本身来pipe理其执行。

然后, test只需要被包装而不是.run()

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

应该用.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); 

其他快速使用:

  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 } ); });